简体   繁体   English

python如何在块例外情况下捕获自定义异常?

[英]How does python catch custom exceptions in except block cases?

Suppose I have the following custom exception. 假设我有以下自定义异常。

class CustomException(TypeError):
    def __init__(message, code):
        super().__init__(f'{code}: message')
        self.code = code

How does python know when to catch my exception in the following code? python如何在以下代码中知道何时捕获我的异常?

try:
    x = doSomething(a, b, c)
except CustomException:
    raise

when I implement the doSomething() function, must it explicitly throw a CustomException in order for it to be caught? 当我实现doSomething()函数时,是否必须显式抛出CustomException以使其被捕获? Like, for built-in exception classes, code can throw an exception like a KeyError and we don't have to explicitly say raise KeyError whenever we do something with a dictionary. 就像,对于内置的异常类,代码可以抛出诸如KeyError之类的异常,并且我们在使用字典进行操作时不必显式地声明raise KeyError

Any code that raises an exception has done so explicitly, including KeyError . 任何引发异常的代码都明确地这样做,包括KeyError No special handling is needed for custom exceptions versus the built-in types. 与内置类型相比,自定义异常不需要特殊处理。 A try...except can only catch an exception if one has been raised by code executed by any statement inside the try . try...except仅可在try内任何语句执行的代码引发异常的情况下捕获该异常。 This includes any further function calls, calls chain together into a callstack. 这包括任何其他函数调用,这些调用链接在一起成为一个调用堆栈。

In the following example 在下面的例子中

>>> d = {}
>>> d['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'foo'

the KeyError doesn't spring out of nothingness, the Python dict implementation raises that exception explicitly. KeyError并非一无是处,Python dict实现显式引发了该异常。 This may not always be obvious because native code (code implemented in C here) doesn't show up in the Python traceback. 这可能并不总是很明显,因为本机代码(此处是用C实现的代码)未显示在Python追溯中。

For the d[...] subscription operation the dict_subscript() function calls _PyErr_SetKeyError(key); 对于d[...]订阅操作, dict_subscript()函数调用_PyErr_SetKeyError(key); , a helper function that uses PyErr_SetObject() , the C equivalent of raise to raise the KeyError(key) exception. ,这是一个使用PyErr_SetObject()的帮助程序函数, PyErr_SetObject()的C语言等效于raise引发KeyError(key)异常的raise。

Catching exceptions works the same for all exception types, custom exceptions are not special here. 捕获异常对于所有异常类型都相同,自定义异常在此并不特殊。 When an exception is raised the normal code flow is interrupted, and the callstack is unwound until an active try statement is encountered, and then any exception handlers are tested, in order of definition in the source code, with isinstance(active_exception, ExceptionClassBeingHandled) . 引发异常时,正常的代码流被中断,并且取消调用堆栈,直到遇到活动的try语句为止,然后按照源代码中定义的顺序使用isinstance(active_exception, ExceptionClassBeingHandled)测试任何异常处理程序。

If nothing catches the exception, Python continues unwinding the callstack until it reaches the last stack frame, at which point Python would exit with a stack trace if nothing caught the exception. 如果没有异常捕获到异常,Python将继续展开调用堆栈,直到到达最后一个堆栈帧为止,此时如果没有异常捕获到异常,Python将退出并带有堆栈跟踪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM