Python – Exception handling

Python provides exception handling mechanism to handle the Exceptions when something went wrong in the Program. Python interpreter reads the code and throws an Exception when something went wrong; if the mechanism is provided to handle the Error, the Program execution continues, otherwise the Program terminates.

Very good example of Exception is Division by Zero error which occurred when attempt to divide some value by 0 (zer0).  Below code example shows the Error and observe that the program terminates without executing the statements after the statement where the Error occurred.

>>> def abc():
...    print("Hello!")
...    a = 20
...    print(a/0)
...    print(a/2)
... 
>>> abc()
Hello!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in abc
ZeroDivisionError: division by zero

Exception handling

When some thing went wrong in the code, Python interpreter raises an exception. Python provides Exception handling mechanism to handle the Exception to avoid unexpected program termination.

Python provides try , except and finally statements to handle Exceptions. We will look at each one these statements.

try Block

This block starts with try statement; contains the group of statements and Python raises an Exception when an error occurred. Instead of terminating the Program, Python looks for Exception handlers for the Exceptions raised. Where Exception handlers are defined? Program has to define the exception handlers inside the except Block.

except Block

except statement will start this block. This block contains group of Exception handlers. Each exception handler will be separated by else statement. Related exception handler is going to execute when an Exception occurred.

finally Block

The statements defined in the finally block are going to execute always; usually we put the clean-up code here.

Let’s put all together and re-write our above program to handle the Divide by Zero Exception.

>>> def abc():
...    try:
...       print("Hello!")
...       a = 20
...       print(a/0)
...    except:
...       print("Exception raised and handled")
...       print(a/2)
...    finally:
...       print("Finally block executed")
... 
>>> abc()
Hello!
Exception raised and handled
10.0
Finally block executed

We discuss more topics in my Upcoming Articles.

/Shijit/

Python – Exception handling

Leave a Reply

Your email address will not be published.

Scroll to top