Python Exception Handling

By | April 12, 2021
Python Exception Handling

In this tutorial, we will discuss how to tackle if any exception occurs in the program. We will also learn all the exceptions handling like try, except and finally.

Python Exception Handling

Allowance Handling

As we know exceptions are the unexpected errors occur in the program at the time of execution.

So, Exception Handling is a mechanism that detects the exception code and separates it from the rest of the code so the program does not fall.

In python, we can use try, except, and final statement to handle the exception.

Catching Exception

We use try and except keywords to catch the exception, and throw an alternate way to deal with the exception respectively.

Inside the try statement block, we write a code that could get an exception during the run time and if any exception occurs the exception statement block gets executed.

What if there is no exception occur in try block?


If there is no exception in try block the except block won’t execute.

try….except Syntax


    #try block


    #except block



for i in [2,1,0,3]:
        print("there is an exception in try block because we are dividing 2 with",i )




there is an exception in try block because we are dividing 2 with 0


Behind the code:

Here in the above example when the i iterate through the list [2,1,0,3] and when its value became 0 it divides 2, this raises a ZeroDivisionError and so the except block gets executed.

Catch Specific Error

We can pass some specific kind of error along the except statement so that it only gets executed when the try block throws that same error.

We use tuple and set errors as its elements when we want to specify more than one error with except method.



except ZeroDivisionError:
    print("the try statement has zero divison error")

except ValueError:
    print("the try block has value error")


the try block has value error

Raise Error

In python we have a raise keyword which is used to create error, we can also pass a message along with the error so the user could understand why specifically this error raises.

raise Syntax:

raise Error_name(“message”)


raise ValueError ("There is a Value Error in the program")


ValueError: There is a Value Error in the program


With the try, except statements, we can also add a finally statement. The code inside the finally block will execute in every case, no matter whether the try, or except statement get executed.   

finally, Syntax:

    # try block
    # except block
    # finally block 



    print("there is an error in the try block")

    print("it will always execute")


there is an error in the try block

it will always execute.
Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published. Required fields are marked *