Python Exceptions: Part Five

exceptions

The Raise Statement

One of the statements not yet covered in this series on exceptions is the raise statement. To trigger excepts explicitly in Python, you can code raise statements. Their general form is simple – a raise statement consists of the word raise, optionally followed by the class to be raised or an instance of it:

	raise  # Raise an instance of a class
	raise  # Make and raise instance of a class
	raise  # Re-raise the most recent exception

The first raise form presented here is the most common one. We provide an instance directly, either created before the raise or within the raise statement itself. If we pass a class instead, then Python will call the class with no constructor arguments to create an instance to be raised. This form is equivalent to adding parenthesis after the class reference. The last form re-raises the most recently raised exception. It is commonly used in exception handlers to propagate exceptions that have been caught.

With built-in exceptions, the following two forms are equivalent:

	raise IndexError
	raise IndexError()

Both examples raise an instance of the exception class named, although the first creates the instance implicitly. We can also create the instance ahead of time, because the raise statement accepts any kind of object reference:

	my_exc = IndexError()
	raise my_exc

	my_excs = [IndexError, TypeError]
	raise my_excs[0]

When an exception is raised, Python sends the raised instance along with the exception. If a try includes an except name as X: clause, the variable X will be assigned the instance provided in the raise:

	try:
		...
	except IndexError as X: 
		...

The as is optional in the try handler. If it is omitted, the instance is simply not assigned to to a name. Including it allows the handler to access both data in the instance and methods in the exception class.

This model works the same for user-defined exceptions coded in classes:

	class MyExc(Exception): pass
	...
	raise MyExc('wooble')
	...
	try:
		...
	except MyExc as X:
		print(X.args)

Regardless of how exceptions are named, they are always identified by instance objects, and at most one is active at any given time. Once caught by an except clause anywhere in the program, an exception dies unless it is re-raised by another raise statement or error.

A raise statement that does not include an exception name or extra data value simply re-raises the current exception. This form is typically used if you need to catch and handle an exception, but you don’t want the exception to die in your code. Running a raise this way re-raises the exception and propagates it to a higher handler.

Finally, Python (3.0 and above) also allows an optional from clause:

	raise exception from otherexception

When the from is used, the second expression specifies another exception class or instance to attach to the raised exception’s __cause__ atrribute. If the raised exception is not caught, Python prints both exceptions as part of the standard error message:

>>> try:
... 	1/0
...	except Exception as E:
...	raise TypeError('Not good') from E

When an exception is raised inside an exception handler, a similar procedure is followed implicitly. The previous exception is attached to the new exception’s __context__ attribute and is again displayed in the standard error message if the exception goes uncaught.

External Links:

Handling Exceptions at Python Wiki Built-in Exceptions at docs.python.org