Saturday, April 21, 2012

Error Handling Part 3


Hello everyone in this post, I will discussing something more about the Error Handling, So now we should know how to Handle Error with Try and Except, and we have also seen the use of while statement to keep our program alive.

Now here is something new, we will continue with our old script, div.py, so lets open up the script:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except SyntaxError:
        print "Error With Your Syntax"
    except NameError:
        print "Idiot, I dont Understand You"
    except ZeroDivisionError:
        print "Integer cannot be divided by me with Zero"
    except TypeError:
        print "Hmm...Sumthingz Fishy Here"
    except KeyboardInterrupt:
        print "Hey You aborted Me"
print "------------------------"
print "[+] EOF Script"


So this worked fine in the last, and this is fine if the script a small one like this one, what if you have a huge script where you have to handle many Errors, the length of the program would just keep increasing, so we wrap the common ones or similar ones in parenthesis under one except block, remember, we you write a script, try to make the script as small as possible, and also the code should be readable, now our modified script would be:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except (SyntaxError, NameError, ZeroDivisionError, TypeError, KeyboardInterrupt):
        print "Error: Session Aborted"
print "------------------------"
print "[+] EOF Script"

So we see here that we have placed all the exceptions errors under a single except block. so this script would display "Error: Session Aborted" for every the errors. Now this is just to show you, the way you handle the errors for your script depends on the business needs or probably the behavior of your script.

Another thing to discuss in this post, assume you are writing a huge script, its not possible to type a customed error every time for every error. So we display the error that Pythons throws, but after handling the exception. Working again with the same script:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except (SyntaxError, NameError, ZeroDivisionError, TypeError, KeyboardInterrupt) as e:
        print "Error: ", e
print "------------------------"
print "[+] EOF Script"

On executing the script, we would get a short error message as to why the error occurred. Try this out.

Thats all for this post, hope it was informative.

Thank You!

0 comments:

Post a Comment