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.



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.


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


Output: Error Occurred!!

Finally Statement:

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


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



Answer is: 2.0
It will execute
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.


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.