O'Reilly logo

Python 3 Object Oriented Programming by Dusty Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required