Instagram
youtube
Facebook
Twitter

Python Exception Handling

Whenever we create any program in python there must be a chance that it gets an error during execution. The error may occur due to a syntax error, invalid inputs, or because of any other reason. So, when a python program gets an error the whole program stop working or the flow of the program gets changed. To deal with these events the concept of exception handling comes. In this tutorial, we’ll learn about python exception handling.

What is an Exception in Python?

An Exception is a condition that occurs during the execution of the program and disrupts the normal flow of the program. When python comes across a condition it can’t handle an exception is raised. So, when a python program throws an exception we have to handle it else the program stops working.

What is Exception handling?

Exception handling is a process of handling unexpected events that occur during the execution of the program. Exception handling is the process that deals with these unexpected events to avoid program failure.

Difference between Syntax Errors & Exceptions

Syntax Errors - Syntax errors are the errors that occur because of invalid syntax such as incorrect spelling, wrong labels, etc.

Exceptions - Exceptions occur when the program is correct by syntax but results in an error during the compilation. Sometimes it stops the execution of the program and sometimes it changes the normal flow of the program.

Exception handling using try and except

In python any exception can be handled using the try and except clause. We have to write all the code and logic inside the try clause and we have to write code to handle exceptions inside the exception clause.

Example:

def add(a,b):
    try:
        print(a+b)
    except:
        print("error occurred!")
add(2,3)
add("a",5)

Here, we have created an add function. inside add function we used the try clause to print the sum of a and b. and, we have used except clause to handle exceptions.

Output:

5
error occurred!

Catching and handling specific exceptions

We can also catch and handle a specific exception in python. To handle a specific exception we can declare the name of the exception after except clause. 

Example:

def add(a,b):
    try:
        print(a+b)
        print(a%b)
    except TypeError:
        print("TypeError Occurred")
    except ZeroDivisionError:
        print("ZeroDivisionError occurred")
add("a",2)
add(2,0)

Here, we have created an add function. inside add function we used the try clause to print the sum and division of a and b. and, we have used except TypeError clause to handle TypeError and except ZeroDivisionError to handle ZeroDivisionError.

Output:

TypeError Occurred
2
ZeroDivisionError occurred

Raising Exceptions in Python

We can raise an exception in the python program forcefully with the help of the raise keyword. There are many ways to raise exceptions in python. We can also pass values to our exceptions to clarify why that exception has occurred.

Example:

a=0
if a==0:
    raise Exception("error occured!")

Here, we have declared a variable as a. then we have used an if condition. inside if condition we have used raise clause to raise an exception as "error occurred".

Output:

line 3, in <module>
    raise Exception("error occured!")
Exception: error occured!

Using Else with Try clause

In any program, there may be some situations when we want to run a certain code block and if the code runs successfully without raising an exception we want to print the final answer. In these types of situations, we can use else with the try clause.

Example:

def add(a,b):
    try:
        ans=a+b
    except TypeError:
        print("error occurred!")
    else:
        print(ans-2)
add(2,3)
add("a",5)

Here, we have created an add function. inside add function we used the try clause to print the sum of a and b. and, we have used except TypeError clause to handle TypeError. then we used the else function to print the answer if it gets terminated successfully in the try block.

Output:

3
error occurred!

Using Finally clause in python

In python, we can use the finally keyword after the try and except clause. It is generally used to print the final statement or to release external resources. the finally code block is always executed even if the try block works successfully or if an exception occurs.

Example:

def add(a,b):
    try:
        print(a+b)
    except:
        print("error occurred!")
    finally:
        print("code ended")
add(2,3)
add("a",5)

Here, we have created an add function. inside add function we used the try clause to print the sum of a and b. and, we have used except clause to handle exceptions. then we used the finally keyword to print the final statement.

Output:

5
code ended
error occurred!
code ended