The raise Statement

A raise statement forces an exception to be raised. One form is

raise exception-expression, description-expression

In our denominator example, it raises a specific exception.

>>> raise ZeroDivisionError, "Sequence has a Zero value in the denominator"
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: Sequence has a Zero value in the denominator

The exception-expression must be of type String or be an instance object. The description-expression is optional. If you use raise with no exception-expression, it reraises the last exception.

You can easily define your own exception using a string variable.

 >>> badListForm = 'badListForm' >>> try: ... raise badListForm, "The list had a malformed tuple" ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.