Exception Handling
Exception handling is the process of responding to unwanted or unexpected events when a
computer program runs. Exception handling deals with these events to avoid the program or
system crashing, and without this process, exceptions would disrupt the normal operation of a
program.
Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error
(something in the program goes wrong).
When these exceptions occur, the Python interpreter stops the current process and passes it to
the calling process until it is handled. If not handled, the program will crash.
Python try...except
try….. except blocks are used in python to handle errors and exceptions. The code in try block
runs when there is no error. If the try block catches the error, then the except block is executed.
Syntax:
try:
#statements which could generate
#exception
except:
#Soloution of generated exception
Example:
try:
num = int(input("Enter an integer: "))
except ValueError:
print("Number entered is not an integer.")
Output:
Enter an integer: 6.022
Number entered is not an integer.
Ai theory-
I'll explain exception handling in Python using simple, relatable examples that build
from basic concepts to more complex ones.
Think of Exceptions Like Real Life Problems
Imagine you're cooking dinner. Things can go wrong:
• You might run out of ingredients (like a missing file)
• The stove might not work (like a broken connection)
• You might burn the food (like invalid input)
Exception handling is like having backup plans for when things go wrong.
The Basic Idea
Without exception handling, your program crashes when something goes wrong:
python
# This will crash your program
age = int(input("Enter your age: ")) # What if user types "abc"?
print(f"You are {age} years old")
With exception handling, you can handle the problem gracefully:
python
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except ValueError:
print("That's not a valid number! Please enter a number." )
Let's Break Down the Parts
1. try block - "Let me attempt this"
python
try:
# "I'm going to try to do this risky thing"
result = 10 / 0
2. except block - "If something goes wrong, do this instead"
python
except ZeroDivisionError:
# "If I can't divide by zero, I'll do this instead"
print("Oops! Can't divide by zero")
Real-World Example: Reading a File
python
# Imagine you're trying to read a shopping list from a file
try:
with open("shopping_list.txt", "r") as file:
shopping_list = file.read()
print("Your shopping list:")
print(shopping_list)
except FileNotFoundError:
print("I couldn't find your shopping list file!")
print("Creating a new one...")
with open("shopping_list.txt", "w") as file:
file.write("milk\nbread\neggs")
Multiple Problems, Multiple Solutions
python
def divide_numbers():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 / num2
print(f"Result: {result}")
except ValueError:
print("Please enter valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Something unexpected happened: {e}")
The Complete Structure Explained
python
try:
# "I'm going to try this risky operation"
risky_operation()
except SpecificError:
# "If this specific thing goes wrong, do this"
handle_specific_error()
except Exception as e:
# "If anything else goes wrong, do this"
print(f"Unexpected error: {e}")
else:
# "If nothing went wrong, do this extra thing"
print("Everything worked perfectly!")
finally:
# "No matter what happened, always do this"
cleanup_resources()
A Practical Example: User Login
python
def login_user():
try:
username = input("Username: ")
password = input("Password: ")
if not username:
raise ValueError("Username cannot be empty")
if len(password) < 6:
raise ValueError("Password too short")
# Simulate checking credentials
if username == "admin" and password == "password123":
print("Login successful!")
return True
else:
raise Exception("Invalid credentials")
except ValueError as e:
print(f"Input error: {e}")
return False
except Exception as e:
print(f"Login failed: {e}")
return False
else:
print("Welcome to the system!")
finally:
print("Login attempt completed")
# Try it out
login_user()
Why This Matters
Without exception handling:
• Your program crashes
• Users see scary error messages
• You lose data or progress
With exception handling:
• Your program continues running
• Users get helpful messages
• You can log errors for debugging
• You can provide alternative solutions
Common Mistakes to Avoid
python
# DON'T do this - too broad
try:
some_code()
except:
pass # Ignoring all errors silently
# DO this instead - be specific
try:
some_code()
except ValueError:
print("Invalid input provided")
except FileNotFoundError:
print("Required file is missing")
The key insight is that exception handling is about being prepared for things that might
go wrong and having a plan for each situation, just like having a first aid kit or insurance
- you hope you won't need it, but you're glad it's there when you do.