Skip to main content

Python Exception Handling: Try and Except and Finally Statement

It is an Event, which occurs during the execution of the program.

This type of error occurs whenever syntactically correct Python code results in an error. This error does not stop the execution of the program, but it changes the normal flow of the program. It occur when Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.

Example:

print(2/0)

Output: ZeroDivisionError: division by zero

Exception handling with try, except and finally

Try and Except Statement 

try statement can have more than one except clause, to specify handlers for different exceptions. Here except is used to handle the error.

Example:

def divide(x, y):
    try:
        result = x/y
        print("Answer is :",res)
    except ZeroDivisionError:
        print("Error Occurred!!")

divide(2,0)

Output: Error Occurred!!

Finally Statement:

It always executes after normal termination of try block or after try block terminates due to some exception.

Example:

def divide(x,y):
    try:
        res = x/y
        print("Answer is:",res)
    except ZeroDivisionError:
        print("Can't divide by zero")
    finally: 
        print("It will execute") 

divide(6,3)

Output:

Answer is: 2.0
It will execute
Tags
Submitted by devanshi.srivastava on July 27, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.