Exception Handling in Python
Introduction
In everyday life, unexpected situations may occur while performing a task.
Examples
ATM runs out of cash.
Internet connection is lost during online payment.
Mobile battery becomes empty.
Similarly, while executing a Python program, unexpected errors may occur. These are called
Exceptions.
Instead of stopping the entire program, Python provides Exception Handling to manage these
errors gracefully.
Definition
Exception Handling is a mechanism used to detect and handle runtime errors so that the
program continues executing normally without crashing.
What is an Exception?
An Exception is an error that occurs during the execution (runtime) of a program.
Example
a = 10
b = 0
print(a/b)
Output
ZeroDivisionError: division by zero
Here,
Program starts successfully.
Error occurs while executing.
Python stops the program.
Why Exception Handling is Needed?
Without Exception Handling
Program Starts
↓
Runtime Error
↓
Program Stops
With Exception Handling
Program Starts
↓
Runtime Error
↓
Exception Handled
↓
Program Continues
Advantages
✔Prevents program crash
✔Improves user experience
✔Makes software reliable
✔Helps debugging
✔Allows graceful termination
Types of Errors in Python
Error Type Meaning Example
Syntax Error Wrong grammar Missing colon
Runtime Error (Exception) Error during execution Divide by zero
Logical Error Wrong output Wrong formula
Example of Syntax Error
if True
print("Hello")
Output
SyntaxError
Example of Runtime Error
print(10/0)
Output
ZeroDivisionError
Example of Logical Error
length = 10
breadth = 5
area = 2*(length+breadth)
print(area)
Output
30
Correct answer should be 50.
Common Python Exceptions
Exception Cause
ZeroDivisionError Division by zero
NameError Variable not defined
TypeError Invalid data type operation
ValueError Invalid value
IndexError List index out of range
KeyError Dictionary key not found
FileNotFoundError File does not exist
AttributeError Invalid object attribute
Exception Cause
ImportError Module not found
Exception Handling Syntax
try:
Risky Code
except:
Handle Error
finally:
Always Executes
Flow Diagram
Program Starts
│
▼
try Block Executes
│
┌────────────┴────────────┐
│ │
No Exception Exception Occurs
│ │
▼ ▼
Skip except Block except Block Executes
│ │
└────────────┬────────────┘
▼
finally Block Executes
│
▼
Program Ends
The try Block
The try block contains code that may generate an exception.
Example
try:
num = int(input("Enter Number: "))
print(100/num)
The except Block
The except block executes only if an exception occurs.
Example
try:
num = int(input("Enter Number: "))
print(100/num)
except:
print("An error occurred.")
Output
Enter Number: 0
An error occurred.
Program does not crash.
Handling Specific Exceptions
Instead of handling all errors together, Python allows handling individual exceptions.
Example
try:
num = int(input("Enter Number: "))
print(100/num)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Enter only integers.")
Sample Outputs
Case 1
Input
0
Output
Cannot divide by zero.
Case 2
Input
abc
Output
Enter only integers.
Multiple Except Blocks
try:
x = int(input())
print(10/x)
except ZeroDivisionError:
print("Division by zero")
except ValueError:
print("Invalid Input")
except:
print("Unknown Error")
Python checks each except block from top to bottom.
The finally Block
The finally block always executes.
Whether
Exception occurs ✔
No exception occurs ✔
It is mainly used for
Closing files
Closing database connection
Releasing resources
Syntax
try:
Statements
except:
Statements
finally:
Statements
Example
try:
print(10/2)
except:
print("Error")
finally:
print("Program Finished")
Output
5.0
Program Finished
Example with Exception
try:
print(10/0)
except:
print("Cannot Divide")
finally:
print("Program Finished")
Output
Cannot Divide
Program Finished
Real-Life Example
Suppose a bank ATM.
Insert Card
↓
Enter PIN
↓
Withdraw Money
↓
Error?
↓
Show Message
↓
Return Card (Always)
Returning the ATM card is like the finally block.
Program: Safe Division
try:
a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Second number cannot be zero.")
except ValueError:
print("Please enter only integers.")
finally:
print("Thank You.")
Program: File Handling with finally
try:
file = open("[Link]","r")
print([Link]())
except FileNotFoundError:
print("File not found.")
finally:
print("Execution Completed.")
Program: List Index Error
try:
numbers = [10,20,30]
print(numbers[5])
except IndexError:
print("Index does not exist.")
finally:
print("Done")
Summary Table
Keyword Purpose
try Contains risky code
except Handles exceptions
finally Executes always