Advanced Exception Handling - finally, Multiple Exceptions and Custom Exceptions

File Handling and Exception Handling

Learning Outcome

5

Connect raise with custom exceptions.

4

Apply else vs finally to real scenarios.

3

Recognize when finally runs and why.

2

Identify ways to handle multiple exceptions.

1

Understand the complete try structure.

The Restaurant Kitchen

A kitchen matches each problem to a fix:

burnt dish remade,
gas leak evacuated.

Every night, gas off,
doors locked, no matter what.

A peanut allergy gets
its own named alert.

Core idea: matched fixes = multiple exceptions;
closing routine = finally;
named alert = custom exception.

Transition to Technical Concept: Think About It

A program divides 100 by user input. Typing “abc” and typing 0 both fail. Same response for both?

Expected Answer: No. Like a burnt dish vs a gas leak, ValueError and ZeroDivisionError need different responses.

Exactly! First, let’s see the full structure that makes this possible.

The Complete try Structure

Key Point: Order is always try → except → else → finally. try needs at least one except or finally.

Why it matters: Keep only the risky line in try, and catch errors only where you can actually respond.

  • try holds the code that might fail.
  • except runs only if an error occurs.
  • else runs only if no error occurred.
  • finally runs every time.

Handling Multiple Exceptions

Separate blocks give a
different response per error.

Grouped in brackets give the same
response for several errors.

as e captures the exact error
message for debugging.

Order matters: Python runs only the first match,
so put specific errors before general ones.

Code:

except (ValueError, ZeroDivisionError):

The finally Block

finally runs when:

  • try succeeds
  • an error is handled
  • an error is unhandled (finally runs, then the crash happens)
  • try hits a return

Uses: Closing DB connections, releasing locks, deleting temp files.

finally vs with: with closes files; finally handles any cleanup.

Raising Exceptions Yourself

  • raise stops execution when input shouldn’t continue.
  • It signals “I can’t continue” instead of returning a wrong result.
  • A bare raise inside except re-raises the error after logging.

Code:

raise ValueError
("Marks cannot be negative")

Custom Exceptions

Define: class
InsufficientBalanceError(Exception):

Raise it where the rule breaks.

Catch it like any exception.

Why it matters: The meaning lives in the error type, not in fragile message text.

  • Names end in “Error”. A base like BankingError catches all related errors.
  • Inherit from Exception, not BaseException, which covers Ctrl+C and exits.

else Block vs finally Block (Comparison)

A Simple Way to Remember

Think & Discuss: A ValueError with a message works too. So why do banking and LMS apps build their own exception classes?

else celebrates,

finally cleans up.

except rescues,

try attempts,

Real-World Applications: else or finally?

Summary

5

raise signals problems; custom exceptions name them.

4

else is for success, finally is for cleanup.

3

finally always runs, even on crash or return.

2

Separate or group exceptions; specific comes first.

1

try, except, else, and finally each have one job.

Quiz

Which except order is correct?

A. Exception, then FileNotFoundError

B. FileNotFoundError, then Exception

C. Either order works

D. Only one except is allowed

Quiz-Answer

Which except order is correct?

A. Exception, then FileNotFoundError

B. FileNotFoundError, then Exception

C. Either order works

D. Only one except is allowed

File Handling and Exception Handling - Advanced Exception Handling - finally, Multiple Exceptions and Custom Exceptions

By Content ITV

File Handling and Exception Handling - Advanced Exception Handling - finally, Multiple Exceptions and Custom Exceptions

  • 116