Flow-control structures: Difference between revisions

Content added Content deleted
Line 332: Line 332:


An exception can be re-raised by simply calling the ''raise'' statement without any arguments (from within any exception handler). Thus a function can catch an exception, attempt to deal with it, then, if necessary, throw it it back to the next layer out in a given call stack. Uncaught exceptions will be handled by the interpreter by terminating the program and printing an error message and stack trace.
An exception can be re-raised by simply calling the ''raise'' statement without any arguments (from within any exception handler). Thus a function can catch an exception, attempt to deal with it, then, if necessary, throw it it back to the next layer out in a given call stack. Uncaught exceptions will be handled by the interpreter by terminating the program and printing an error message and stack trace.

A custom Exception class is normally declared with the ''pass'' statement as no methods of the parent class are over-ridden, no additional functionality is defined and no attributes need be set. Example:

<python>
class MyException(Exception): pass
</python>

One normally would choose the most similar existing class. For example if MyException was going to be raised for some situation involving an invalid value it might be better to make it a subclass of ValueError; if it was somehow related to issues with inappropriate objects being passed around then one might make it a subclass of TypeError.

In large projects it's common to create an custom application base exception and to have all or most custom exceptions within that application or framework derive therefrom.

To create a "virtual base class" (one which is not intended to be directly instantiated, but exists solely to provide an inheritance to it's derived classes) one normally defines the requisite methods to raise "NotImplementedError" like so:

<python>
class MyVirtual(object):
def __init__(self):
raise NotImplementedError
</python>

It then becomes necessary for any descendants of this class to over-ride the ''__init__()'' method. Any attempt to instantiate a "MyVirtual" object directly will raise an exception.


====Case 1 - Try, Except====
====Case 1 - Try, Except====