CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

Python – Exception handling

Python provides an 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.

A very good example of an Exception is the Division by Zero error which occurred when attempting to divide some value by 0 (zer0).  The below code example shows the Error and observes 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 something went wrong in the code, the Python interpreter raises an exception. Python provides an 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 of 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? The program has to define the exception handlers inside the except Block.

except Block

except statement will start this block. This block contains a group of Exception handlers. Each exception handler will be separated by else statement. A 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 it 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. Required fields are marked *

Scroll to top