Exception Handling
Exception Handling
Objectives:
- Understand what exceptions are.
- Learn why and where exception handling is used.
- Understand how exception handling improves software reliability.
- Explore Python's exception handling syntax with examples.
- Discuss best practices.
What is an Exception?
An exception is an error that occurs during the execution of a program. When an
exception occurs, the program stops and displays an error message.
Examples of exceptions:
- Division by zero: 5 / 0
- Accessing a variable that doesn't exist.
- Reading a file that is not found.
Basic Syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
✅ Examples
Example 1: Handling Divide by Zero:
try:
result = 10 / 0 # Trying to divide by zero will raise an exception
except ZeroDivisionError:
print("You can't divide by zero.") # Handle the exception with a custom message
The finally block in Python is used to define code that should always run, no matter what
happens whether an exception occurs or not.
Best Practices
- Catch specific exceptions (not a generic except).
- Use finally for clean-up actions like closing files.
- Avoid hiding bugs by catching exceptions silently.
- Log errors for debugging.
- Validate inputs before using them.
2. Multiple Exceptions
try:
name = input("Enter your name: ") # Prompt user for name
age = int(input("Enter your age: ")) # Prompt user for age and convert to int
print(f"{name} is {age} years old.") # Display the name and age
except ValueError:
print("Please enter a valid number for age.") # Handle invalid input for age
except Exception as e:
print("An unexpected error occurred:", e) # Catch any other unexpected exceptions
except Exception as e:
# If any error occurs during writing, show the error
print("❌ An error occurred:", e)
finally:
# This block always runs, whether there's an error or not
print("✅ Finished writing to the file.")
except FileNotFoundError:
# Handle case if file doesn't exist
print("❌ File not found. Please create it first.")
finally:
# Message that this step is completed
print("✅ Finished reading the file.")
✅ Step 3: Download the File to Your Computer (Optional)
from google.colab import files # Import module for file operations
# Use Colab's files.download method to download the file to your local system
files.download("example.txt")
try:
check_age(-5) # Try to check an invalid age
except ValueError as e:
print("Error:", e) # Catch and print the custom exception message
6. Custom Exceptions
class InvalidAgeError(Exception):
pass
def validate_age(age):
if age < 0:
else:
print(f"Your age is {age}. Valid age entered.")
try:
age = int(input("Please enter your age: ")) # Ask the user for their age
except InvalidAgeError as e:
print(f"Error: {e}")
except ValueError:
# Handle the case where the user doesn't enter a valid number
Write a Python program that asks the user for a number to divide 100 by. Ensure the
program handles:
After handling the exceptions, the program should display the result of the division (if no
error occurred).
Solution:
def divide_number():
try:
number = int(input("Enter a number to divide 100 by: ")) # Take user input
result = 100 / number # Perform division
print(f"100 divided by {number} is {result}")
except ZeroDivisionError:
print("Error: You cannot divide by zero.") # Handle division by zero
except ValueError:
print("Error: Please enter a valid number.") # Handle invalid input (non-numeric)
except Exception as e:
print(f"An unexpected error occurred: {e}") # Handle any other exceptions
Create a Python program where the user is prompted to enter their age. If the age entered
is less than 18, raise a custom exception called UnderAgeError and display an appropriate
message. Handle the exception and ask the user to input the age again until a valid age
(18 or older) is entered.
Solution: