Classes and Instances as Exceptions

Earlier we defined our own exception using a string object, making it user defined. The new Python way of defining exceptions is with classes and class instances, which means that the raise statement can take the following form:

raise class, class_instance

raise class_instance

In the except clause, you list the name of the class. If the exception instance raised is an instance of that class (a direct instance or an instance of a subclass), except will catch it. The exception class you define should be derived from the Exception class, which is defined in the exception module (exception.py). As of now, this isn't a requirement, but it likely will be in the future. If you use an instance of Exception in conjunction ...

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.