4.2 Handling exceptions
Now let’s look at the tails side of the exception coin. When an exception is raised, how should our code react to or recover from it? We handle exceptions by wrapping any code that might throw an exception inside a try...except clause. The most basic syntax looks like this:
def handler() -> None:
try:
never_returns()
print("Never executed")
except Exception as ex:
print(f"I caught an exception: {ex!r}")
print("Executed after the exception")
If we run this simple script using our existing never_returns() function — which, as we know very well, always throws an exception — we get this output:
>>> handler()
I am about to raise...