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 ...

Get Python 3 Object Oriented Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.