Exception Handling
-
This lesson teaches how to handle runtime errors using exception handling techniques in Python.
What is an Exception?
An exception is a runtime error that occurs during program execution and disrupts the normal flow of the program.
Examples:
Division by zero
Invalid user input
File not found
What is Exception Handling?
Exception handling is the process of catching and handling exceptions so that the program does not crash.
Python uses:
try
except
else
finally
raise
Why Do We Use Exception Handling?
Exception handling helps to:
Prevent program crashes
Handle user errors safely
Improve program reliability
Provide user-friendly error messages
Perform cleanup actions
Basic Structure of Exception Handling
try:
# risky code
except ErrorType:
# handling code
else:
# runs if no error occurs
finally:
# always runs
1️. try Block
What is try?
The try block contains code that may raise an exception.
Using try Block
This code attempts to divide two numbers.
try:
a = 10
b = 2
print(a / b)
2. except Block
What is except?
The except block catches and handles the exception raised in try.
Handling Division Error
This program handles division by zero.
try:
x = 10
y = 0
print(x / y)
except ZeroDivisionError:
print("Error: Cannot divide by zero")
Multiple except Blocks
This program handles different types of errors.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Zero is not allowed")
except ValueError:
print("Please enter a valid number")
3.else Block
What is else?
The else block executes only if no exception occurs in the try block.
Using else Block
This program prints result if no error occurs.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Division by zero error")
else:
print("Result:", result)
4.finally Block
What is finally?
The finally block always executes, whether an exception occurs or not.
👉 Used for cleanup actions.
Using finally Block
This program shows that finally always runs.
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found")
finally:
print("Closing file")
5.Raising Exceptions (raise)
What is raise?
The raise keyword is used to manually trigger an exception.
Syntax
raise ExceptionType("message")
Raising Custom Exception
This program raises an exception if age is below 18.
age = 16
if age < 18:
raise ValueError("Age must be 18 or above")
else:
print("Eligible to vote")
Raising Exception from Function
This function raises an exception for negative numbers.
def check_number(n):
if n < 0:
raise ValueError("Negative number not allowed")
return n
print(check_number(5))
Exception Handling Flow
try → exception occurs → except → finally
try → no exception → else → finally
Common Built-in Exceptions