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)

Mini Quiz

0%

Python - Quiz 20

1 / 5

Q1. Which block contains the code that may generate an exception?

2 / 5

Q2. Which keyword is used to manually generate an exception in Python?

3 / 5

Q3. Which block always executes whether an exception occurs or not?

4 / 5

Q4. When does the else block execute in a try-except statement?

5 / 5

Q5. Which exception is raised when a program attempts to divide a number by zero?

Your score is

The average score is 0%

0%

Mini Project

Mini Project: ATM Withdrawal

Question:

Write a Python program to simulate an ATM withdrawal using exception handling.

Perform the following operations:

  • Accept the account balance and withdrawal amount from the user.
  • Display an error if the user enters a non-numeric value.
  • Raise an exception if the withdrawal amount is greater than the balance.
  • Display “Withdrawal Successful” if the transaction is valid.
  • Display “Thank You for Using the ATM” using the finally block.
View Answer Code
try:
    balance = float(input("Enter Account Balance: "))
    amount = float(input("Enter Withdrawal Amount: "))

    if amount > balance:
        raise Exception("Insufficient Balance")

    print("Withdrawal Successful")

except ValueError:
    print("Enter Numbers Only")

except Exception as e:
    print(e)

finally:
    print("Thank You for Using the ATM")

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top