Friday, September 27, 2013

Exception (Python)

Beside, preventing the user to break your code, I find that exception is useful whenever there is a special case that I can't think about at the moment that is needed to be handled. You can also make it to return a message saying that it had caught a special case, then you will know where the special cases you had missed. Before showing how to catch an error, let's define what is exception.

Exception is a class in Python library, which it handles every error that occurs during the runtime. Every time an error occurs in the runtime, the program stops running and it creates an exception object, then it prints out the trackbacks which contain the code line and a message of the error. The message describes the type of error that had been thrown. Python exception's keyword are raise (thrown: java), except(catch), try and finally. When catching the thrown exception object, list the most specific exception first before the general ones, because Python will search the except from top to bottom. The following example shows that the other except will never reach cause the "except Exception" will always catch the thown error:

________________________________________________________________________________
#Danny Heap
#http://www.cdf.toronto.edu/~heap/148/F13/Lectures/W3/exceptions.py

class SpecialException(Exception):
    pass

class ExtremeException(SpecialException):
    pass

if __name__ == '__main__':
    try:
        1/0
        #raise SpecialException('I am a SpecialException')
        #raise Exception('I am an Exception')
        raise ExtremeException('I am an ExtremeException')
        #1/0
    except Exception as e:
        print(e)
        print('caught as Exception')
except SpecialException as se: print(se) print('caught as SpecialException') raise except ExtremeException as ee: print(ee) print('caught as ExtremeException') #raise
________________________________________________________________________________

Now that you recall how to use Exception, lets go back to the idea that you can catch a special case with exception. Before you go out telling your friends this great idea, let me warn you that this is not a good programming practice, it is just a quick-and-dirty way to keep your code running. If you want to test it propery, create a test class for your code. 
_________________________________________________________________________________
def mean(list, n):
 try:
result = sum(list)/0
except:
print("special case in mean function")
print("List: " + list)
print(n)
_______________________________________________________________________________
Is a good practice to code in an exception handler to ever user input code to prevent them messing up with your code.

No comments:

Post a Comment