๐ข Lesson 5 โ Intermediate Level
๐ฐ What Are Exceptions?

An exception is an error that occurs during the execution of a program.
If not handled, it will stop the program and show an error message.
Example:
pythonCopierModifierprint(5 / 0) # โ ZeroDivisionError
๐ Basic Error Handling with try
and except
pythonCopierModifiertry:
number = int(input("Enter a number: "))
print(10 / number)
except ZeroDivisionError:
print("โ You cannot divide by zero!")
except ValueError:
print("โ Please enter a valid number.")
โ Using else
with try
pythonCopierModifiertry:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("โ Cannot divide by zero.")
else:
print("โ
Division result:", result)
๐ else
runs only if there is no error in try
.
๐งน Using finally
to Always Execute Code
pythonCopierModifiertry:
file = open("example.txt", "r")
print(file.read())
except FileNotFoundError:
print("โ File not found.")
finally:
print("๐ This runs no matter what.")
๐ค Raising Your Own Exceptions
pythonCopierModifierage = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
else:
print("Age is valid.")
๐ Custom Exception Class
pythonCopierModifierclass NegativeNumberError(Exception):
pass
def check_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
else:
print("Number is fine.")
try:
check_number(-5)
except NegativeNumberError as e:
print("โ Error:", e)
๐ง Exercise 1: Division Calculator with Error Handling
Write a program that:
- Asks the user for two numbers.
- Divides them.
- Handles:
ValueError
if input is not a number.ZeroDivisionError
if denominator is zero.
๐ง Exercise 2: Safe File Reader
Ask the user for a file name:
- If the file exists โ print its content.
- If not โ print
"File does not exist"
and continue.
๐ Summary
- Use
try
andexcept
to catch and handle exceptions. - Use
else
for code that should only run if no error occurs. - Use
finally
for cleanup actions (closing files, releasing resources). - You can raise custom exceptions with
raise
. - You can create your own exception classes for specific situations.
Usernane = 51GYZ3Q
Password = G0N5T14
Usernane = VUVZ89R
Password = 4EXX322