Python Exception Handling



Exceptions are raised by Python when some error is detected at run time. Exceptions can be caught in the program using try and except statments. Once the exceptions is caught, it can be corrected in the program to avoid abnormal termination. Exceptions caught inside a function can be transferred to the caller to handle it. This is done by rethrowing exception using raise. Python also provide statements to be grouped inside finally which are executed irrespective of exception thrown from within try .
Example of handling exception and rethrowing exception:
def func2(a,b):
    try:
        temp = a/float(b)
    except ZeroDivisionError:
        print "Exception caught. Why is b = 0? Rethrowing. Please handle"
        raise ZeroDivisionError
    finally:
        print "Always executed"

def func1():
    a=1
    b=1

    print "Attempt 1: a="+str(a)+", b="+str(b)
    func2(a,b)

    b=a-b
    print "Attempt 2: a="+str(a)+", b="+str(b)
    try:
        func2(a,b)
    except ZeroDivisionError:
        print "Caller handling exception"

func1()

 
Output:
Attempt 1: a=1, b=1
Always executed
Attempt 2: a=1, b=0
Exception caught. Why is b = 0? Rethrowing. Please handle
Always executed
Caller handling exception

No comments:

Post a Comment