Monday, February 3, 2014

Week 4 - Exceptions

This week, we started with something that we have never learnt before: Exception. Exceptions should be class objects. The exceptions are defined in the module Exception; it is a built-in class and I can always build new exception as subclasses of it and the python will automatically know it will deal with exceptions. The following Exception can only used as a superclass classes for other exceptions. A typical look of Exception will be this:
class E1(Exception):
       """
       An exception class that is a subclass of Exception.
       """
       pass

class E2 (E1):
       """
       An exception class that is a subclass of E1.
       """   
       pass

def exception_raise_function(x) -> None:

       try:   

        if something:
               raise E1

        else:
               raise E2('hey, I’m E2')
       
        except E1:
               # can print/return/etc. things

        except E2:
               # can print/return/etc. things
In class Exception, a try statement with an except clause that mentions a particular Exception subclass, that clause also handles any exception classes derived from that class. A exception message that coded within the bracket in the raise statement can also be printed when this exception is been raised. A test class could be designed to test the exception code:
def test_exception_raise_function(f, x) -> None:
       """
       f is the name of the exception function, x is the input of the                               functions.
       """

    try:
           if f(x) is None:
                  # can print/return/etc. things
       
    except E1:
           # can print/return/etc. things
   
    except E2:
           # can print/return/etc. things
The raise of a exception can sometimes return something long and messy. Yet, by using designed testing function, one can see whether the exception function was correctly coded by the things it returned.
Python raises exception in case of errors, and I can design codes to deal with these errors. I can use the try statements and except statements to raise exceptions when an error is produced. All exceptions are designed/subclassed from the built-in superclass, Exception class. I am still a little bit confuse about the differences of put try and except statements into different orders or levels of indented if statements, yet I think I have already got some grasp about exception; I just need a bit more practice :D.

No comments:

Post a Comment