SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 09
← Back to Course Index

Exception Handling


On This Page

Module 9: Exception Handling


9.1  What is an Exception?

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.

► A Program That Crashes
price = 500
quantity = 0
per_unit = price / quantity   # This will crash!
⚠ Without Handling
This program crashes with: ZeroDivisionError: division by zero — and the entire program stops running immediately, which is unacceptable in real applications.

9.2  try and except

The try block contains code that might cause an error; the except block runs only if an error occurs, preventing a crash.

► Handling the Same Error Gracefully
price = 500
quantity = 0

try:
    per_unit = price / quantity
    print("Price per unit:", per_unit)
except ZeroDivisionError:
    print("Error: Quantity cannot be zero!")
Output
Error: Quantity cannot be zero!
✓ Instructor Tip
Always catch specific exceptions (like ZeroDivisionError) rather than a bare except: — this makes debugging much easier and avoids silently hiding unrelated bugs.
► Handling Multiple Exception Types
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!")

9.3  The finally Block

The finally block always runs — whether an error occurred or not. It's commonly used for cleanup tasks like closing files or database connections.

► Using finally
try:
    file = open("data.csv", "r")
    print(file.read())
except FileNotFoundError:
    print("Error: File not found!")
finally:
    print("Cleanup complete - this always runs.")
Output
Error: File not found!
Cleanup complete - this always runs.

9.4  The else Block

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.

► Using try-except-else-finally Together
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.")

9.5  raise — Manually Triggering Exceptions

You can manually trigger an exception using raise — useful when your own business logic detects an invalid situation that Python itself wouldn't catch.

► Using raise
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)
Output
Enrollment Error: Student must be at least 16 years old to enroll.

9.6  Custom Exceptions

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.

► Creating a Custom Exception
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)
Output
Payment Error: Paid amount is less than the due fee of Rs.12000
ℹ Real-World Use Case
Custom exceptions like InsufficientFeeError or InvalidCouponError make error messages far more meaningful in real business applications compared to generic Python errors.

9.7  Common Built-in Exceptions

ExceptionWhen It Occurs
ValueErrorInvalid value, e.g. int('abc')
TypeErrorWrong data type used, e.g. '2' + 2
ZeroDivisionErrorDividing any number by zero
IndexErrorAccessing a list index that doesn't exist
KeyErrorAccessing a dictionary key that doesn't exist
FileNotFoundErrorTrying to open a file that doesn't exist
AttributeErrorCalling a method that doesn't exist on an object

9.8  Practice Questions

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.

9.9  Module Quiz (MCQs)

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?

ℹ Answer Key
1-c, 2-d, 3-b, 4-b, 5-b

9.10  Module Assignment

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.

9.11  Interview Questions — Module 9


9.12  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.