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
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
finallyblock.
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.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.