Handling exceptions
Now let's look at the tail side of the exception coin. Namely, if we encounter an exception situation, how should our code react to, or recover from it? We handle exceptions by wrapping any code that might throw one (whether it is exception code itself, or a call to any function or method that may have an exception raised inside it) inside a try
...except
clause. The most basic syntax looks like this:
try: no_return() except: print("I caught an exception") print("executed after the exception")
If we run this simple script using our existing no_return
function, which we know, very well, always throws an exception, we get this output:
I am about to raise an exception I caught an exception executed after the exception
The no_return
function happily informs us that it is about to raise an exception. But we fooled it and caught the exception. Once caught, we were able to clean up after ourselves (in this case, by outputting that we were handling the situation), and continue...