Exception Handling in Python

In this blog, we will see how to handle exceptions in Python application. If you are new to Python, please read my previous blog - Introduction to Python Programming

This blog will help you to understand try, except and finally block  in Python code. Exception handling is very important to create a stable robust application in Python.

In any programming language, handling errors or exceptions is very important. If you write good code, then the code must have the capabilities to handle the errors.

Python Exception Handling : Types of Error

Compile Time Error -

If there is a syntax error or spelling error in any of the keyword, you will get compile time error.

Run time Error -

If the application throws error while processing output, it is called as Run time error.
For eg - Division by zero is the most common run time error example.

Logical Error -

In case user doesn't get desired output, it is a logical error. It means either there is an error in calculation or the logic implemented to return output.

Exception Handling in Python

Exception handling in Python is similar to other programming language, the only difference is way of writing.
Now we will see how can we handle exception in Python code by an example.
Let's write below code and execute this -

i = 10
j = 1
print(i/j)
print("Next statement")
There is no compile time error in above code and it will run as expected with below output.
10.0
Next statement

Now, let's change the code -

i = 10
j = 0
print(i/j)
print("Next statement")

In general, the code doesn't have any compile time error.
But, it will have Run time error. Above code will give below error.

ZeroDivisionError: division by zero
The error is OK, but, these type of exception messages are not user friendly, user can not understand these errors. Also, Next Statement will not be printed/executed here.

To handle these kind of exceptions or errors, we will use try, except, finally in Python.

Syntax to handle exception in Python -

Instead of try, catch, finally like other programming language, we have try, except and finally in Python to handle exceptions errors.

What is try-except in Python?

try:
    #Write Logic Here
except Exception:
    #Write message to show when exception occurred

try -

try block in Python is the code where exception may occur. In case of any error or exception.

control will go to except block.

except -

Except block in Python is to get the error message and log it some where or display this for user.

Following is an example which shows how to handle exception in Python.

Python Exception Handling Examples

i = 10
j = 0
try:
    print(i/j)
except Exception:
    print("There is some error.")
print("Next statement")

Output - 
There is some error. 
Next statement

In above code, we have printed our own error message if occurred.
Now, suppose you want to print the exact exception message thrown by the code.

We can represent ex as Exception object to show the error message. See below code.

i = 10
j = 0
try:
    print(i/j)
except Exception as ex:
    print(ex)
print("Next statement")

In above code, it will print exact error message.

Finally block in Python -

Finally block is an important part of exception handling in Python specially when you are working with database connection. If you open a database connection for any transaction then please make sure that you close the connection post completion of your transaction. To do this we use finally block.

Benefit of finally block is that the code written inside this block will be executed at any cost i.e. if we get an error or if we don't get an error.

Python Exception Handling Example with Finally


try:
    print('Database Connection Open')
    print('Code executed')
except Exception as ex:
    print('There is some error', ex)
finally:
    print('Close Database Connection')

Above code will produce below result -

Database Connection Open
Code executed
Close Database Connection


We can also used specific Exception classes in Python.


ZeroDivisionError - It catches the exception, in case there is an attempt to divide an integer or decimal value by zero(0).


FileNotFoundError - The exception which is thrown when an attempt to access a file that does not exist on given path.


ArithmeticError - The exception that is thrown for errors in an arithmetic, casting, or conversion operation.

Exception - This is the base Exception class in Python

Below code demonstrate few specific exception classes available in Python.

i = 10
j = 0
try:
    print(i/j)
    print('Code executed')
except ZeroDivisionError as ex1:
    print(ex1)

except FileNotFoundError as ex2:
    print(ex2)

except ArithmeticError as ex3:
    print(ex3)

except Exception as ex:
    print(ex)

finally:
    print('Execution Completed')


Handle Multiple Exceptions in single Except Block -

In Python, a single except block can handle multiple Exception type.
But, how can we handle multiple Exception in a single except block.
Let's see below Code sample.

try:
   a = int(input('Enter a number'))  
   b = int(input('Enter another number'))  
   print(a/b)
except (ZeroDivisionError,ValueError) as ex:
   print('Exception:-', ex.__class__.__name__)
   print('Exception Details:-', ex)
   print('Please enter valid input')

finally:
    print('Execution Completed')



If you will try to divide by zero, code will throw below error -

Exception:- ZeroDivisionError
Exception Details:- division by zero
Please enter valid input
Execution Completed

If you will enter a string instead of integer value, code will throw below error -

Exception:- ValueError
Exception Details:- invalid literal for int() with base 10: 'ww'
Please enter valid input
Execution Completed

You may notice that same code block is throwing different Exception message why because we have used except block to represent multiple Exception type.

Exception Handling in Python - Summary

In general, Python exception handling is similar to other programming language.
In Python, we have try-except-finally block to handle exceptions.
A single except can handle multiple type of Exceptions. 

Hope you like this blog. Please share this blog within your community.

Previous Blog - Introduction to Python Programming

Watch Video on - Exception Handling in Python


You may like other blogs -
Interview Questions and Answers Series -

Comments