An exception is an error that occurs during program execution and stops the program immediately unless it is handled. Exception handling lets your program respond gracefully to errors instead of crashing.
price = 500
quantity = 0
per_unit = price / quantity # This will crash!The try block contains code that might cause an error; the except block runs only if an error occurs, preventing a crash.
price = 500
quantity = 0
try:
per_unit = price / quantity
print("Price per unit:", per_unit)
except ZeroDivisionError:
print("Error: Quantity cannot be zero!")try:
age = int(input("Enter your age: "))
result = 100 / age
except ValueError:
print("Error: Please enter a valid number!")
except ZeroDivisionError:
print("Error: Age cannot be zero!")The finally block always runs — whether an error occurred or not. It's commonly used for cleanup tasks like closing files or database connections.
try:
file = open("data.csv", "r")
print(file.read())
except FileNotFoundError:
print("Error: File not found!")
finally:
print("Cleanup complete - this always runs.")The else block runs only if the try block completes successfully with no exception — useful for code that should run only when everything went fine.
try:
marks = int(input("Enter marks: "))
except ValueError:
print("Please enter a valid number.")
else:
print("Marks entered successfully:", marks)
finally:
print("Input process finished.")You can manually trigger an exception using raise — useful when your own business logic detects an invalid situation that Python itself wouldn't catch.
def enroll_student(age):
if age < 16:
raise ValueError("Student must be at least 16 years old to enroll.")
print("Enrollment successful!")
try:
enroll_student(14)
except ValueError as e:
print("Enrollment Error:", e)For complex applications, you can define your own exception classes by inheriting from Python's built-in Exception class — giving your errors meaningful, specific names.
class InsufficientFeeError(Exception):
pass
def process_payment(amount, fee_due):
if amount < fee_due:
raise InsufficientFeeError(f"Paid amount is less than the due fee of Rs.{fee_due}")
print("Payment accepted!")
try:
process_payment(5000, 12000)
except InsufficientFeeError as e:
print("Payment Error:", e)| Exception | When It Occurs |
|---|---|
| ValueError | Invalid value, e.g. int('abc') |
| TypeError | Wrong data type used, e.g. '2' + 2 |
| ZeroDivisionError | Dividing any number by zero |
| IndexError | Accessing a list index that doesn't exist |
| KeyError | Accessing a dictionary key that doesn't exist |
| FileNotFoundError | Trying to open a file that doesn't exist |
| AttributeError | Calling a method that doesn't exist on an object |
Basic (5 Questions)
1. Write a try-except block to handle division by zero.
2. Write a try-except block that catches a ValueError when converting text to a number.
3. Add a finally block to any of your earlier programs and explain what it does.
4. Write a program that tries to access index 10 of a 3-item list and handles the IndexError.
5. Write a program that tries to access a missing dictionary key and handles the KeyError.
Intermediate (5 Questions)
1. Write a function that raises a ValueError if a given discount percentage is above 50%.
2. Handle multiple exception types (ValueError and ZeroDivisionError) in a single program.
3. Use try-except-else-finally together in one complete program.
4. Write a program that safely opens a file and handles FileNotFoundError gracefully.
5. Create a custom exception called InvalidAgeError and use it in an age-validation function.
Advanced (5 Questions)
1. Build a robust 'Course Enrollment Validator' that raises custom exceptions for invalid age, invalid course name, and insufficient fee — all handled gracefully.
2. Write a program that keeps asking the user for a number until valid input is given (using a loop with try-except).
3. Create a custom exception hierarchy with a base AppError and two child exceptions.
4. Write a function that processes a list of student ages and reports every invalid entry without crashing the whole program.
5. Build a simple calculator that handles ZeroDivisionError, ValueError, and TypeError all in one program.
Q1. Which block runs only if no exception occurs?
Q2. Which block always runs, error or not?
Q3. Which exception occurs when dividing by zero?
Q4. Which keyword manually triggers an exception?
Q5. What must a custom exception class inherit from?
Assignment: Robust Student Enrollment Validator
Expected Output: A fully working enrollment validator that never crashes, regardless of what invalid input is given, and shows clear, specific error messages.
Use this space to write down key points, doubts, and your own examples from today's session.