如何有效地捕获异常并检查参数是否为非

2024-06-07 17:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您有一个函数,它在某些错误情况下给出异常,在某些情况下返回None(它不是我设计的,我需要使用它)。现在,您需要以相同的方式处理这些错误(向用户显示消息、记录并优雅地退出)。你知道吗

我一直在做这样的事情:

try:
    result = weird_func()
except:
    *same functionality* do something here

if not result:
    *same functionality* do the same here as in the except block

但真的很糟糕。有没有办法巧妙地把这两个卷成一个? 我一直在考虑使用try/finally而不使用except,但它看起来有点奇怪。你知道吗

有什么建议吗?你知道吗


Tags: the函数用户none消息here错误方式
3条回答

falsetru或多或少说过:

result = wierd_func()
assert result

当结果为None时,将引发原始异常或AssertionError。只要任何封闭的尝试都能捕捉断言错误以及wierdèu func所做的任何其他事情,你就很好。你知道吗

为了完整起见,还有:

try:
   return wierd_func() or RuntimeError() # or whatever you'd like to raise:
except:
   return sys.exc_info()[0]

在出现错误的情况下,它总是返回一个异常对象,因此您可以用这种方式进行恢复——但是我不想麻烦:try/catch用于处理错误条件,因此添加assert,然后在一个位置处理所有异常

try:
    result = weird_func()
except TheExceptionYouWantToCatch:
    result = None

if result is None:
    #Whatever you want

将result设置为None是一个选项。你知道吗

try:
    result = weird_func()
except:
    result = None

if not result:
    *same functinality* do the same here as in the except block

或在try中引发异常。你知道吗

try:
    result = weird_func()
    if not result: raise Exception() # or assert result
except:
    *same functinality* do something here

相关问题 更多 >

    热门问题