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?
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? 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.
Any code that raises an exception has done so explicitly, including 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
. 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. This may not always be obvious because native code (code implemented in C here) doesn't show up in the Python traceback.
For the d[...]
subscription operation the dict_subscript()
function calls _PyErr_SetKeyError(key);
, a helper function that uses PyErr_SetObject()
, the C equivalent of raise
to raise the KeyError(key)
exception.
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)
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.