Junior — Middle
What exception in Python cannot be caught using try-except?
sobes.tech AI
Answer from AI
In Python, there are exceptions that cannot be caught using the try-except construct, such as exceptions related to system termination of the program:
- SystemExit — called by the sys.exit() function, terminates the program.
- KeyboardInterrupt — occurs when the user interrupts the program (Ctrl+C).
- GeneratorExit — called when a generator is closed.
Although technically they can be caught, it is not recommended to do so, as they are intended for managing the program's lifecycle. Exceptions that cannot be caught at all are interpreter errors, such as segmentation faults, which are not Python exceptions.
Example:
try:
exit()
except SystemExit:
print("SystemExit caught") # This will work, but is generally not done