Python Exception Handling

In this tutorial, we will learn about exception handling in Python. We will also discuss some important keywords like try and except in Python for exception handling.

What is an Exception?

The exception is an abnormal condition, which occurs during program execution and terminates the flow of a program. Python exception can be ZeroDivisionError, TypeError and many more.

Below example will generate an exception because of division by zero.

#exception : divison by zero is not possible
a=10
print(a/0)

Handling an Exception in Python

In Python, try and except block is used to handle the exceptions.

  • try – It includes statements which may generate an exception.
  • except – If the exception encounter, except block, will execute.
  • finally – It includes important codes which must execute, whether an exception is generated or not.

Syntax: try-except block

try:
    #statements which may generate an exception
except:
    #if the exception occur

In the below example, if we enter a text value instead of the numbers, then it will raise an exception and except block will execute.

try:
    a=int(input("Enter First number"))
    b=int(input("Enter Second number"))
    c=a/b
    print(c)
except ValueError:
    print("Enter Numbers Only")

Multiple except with a try

Multiple except is possible in python, to manage different type of exception.

try:
    a=int(input("Enter First number"))
    b=int(input("Enter Second number"))
    c=a/b
    print(c)
except ValueError:
    print("Enter whole Numbers Only")
except ZeroDivisionError:
    print("Divison by zero is not possible")

Python Finally block

In Python, ‘finally‘ block includes important statements which must be executed. Because ‘finally’ block always executes whether an exception is generated or not.

try:
    a=int(input("Enter First number"))
    b=int(input("Enter Second number"))
    c=a/b
    print(c)
except ValueError:
    print("Enter whole Numbers Only")
except ZeroDivisionError:
    print("Divison by zero is not possible")
finally:
    print("Always Work")

Raise an Exception

We can also throw an exception forcefully using raise keyword in Python.

try:
    a=int(input("Enter First number"))
    b=int(input("Enter Second number"))
    if a<=0 or b<=0:
        raise Exception("Enter Only Positive numbers")
    else:   
        c=a/b
        print(c)
except Exception as e:
    print(e)

In the above example, raise keyword is used to generate an exception if the number is less then or equal to zero. An Exception is caught by except block and e is object of the exception class.

else clause with try-except

In Python exception handling, else block will execute if a try-except block does not throw an exception.

try:
    a=int(input("Enter First number"))
    b=int(input("Enter Second number"))
    c=a/b
except ZeroDivisionError:
    print("Divison by zero is not possible")
else:
    print(c)