我有一个异常实例,需要根据它的类型执行代码。哪种方式更清楚 - 重新引发异常或 isinstance 检查?
重新提高:
try:
raise exception
except OperationError as err:
result = do_something1(err)
except (InvalidValue, InvalidContext) as err:
result = do_something2(err)
except AnotherException as err:
result = do_something3(err)
except:
pass
实例检查:
if isinstance(exception, OperationError):
result = do_something1(err)
elif isinstance(exception, (InvalidValue, InvalidContext)):
result = do_something2(err)
elif isinstance(exception, AnotherException):
result = do_something3(err)
PS。代码用于 django process_exception 中间件,因此在重新引发异常时,我应该except:pass
为所有未知异常编写。