Intermediate Topic 29 of 54 Programming Fundamentals
Exceptions
Objects signalling abnormal conditions that propagate up the call chain.
How it works
Throwing an exception unwinds the call stack until a matching handler (try/catch) is found; if none exists, the program terminates with a stack trace. Exceptions separate the normal flow of code from the error flow, and typed exception classes let handlers respond to specific problems. A finally block runs whether or not an exception occurs.
Step-by-step walkthrough
- parse() hits bad input and raises an exception.
- The call stack unwinds, abandoning parse().
- process() has no handler so unwinding continues.
- main() has a try/except that catches it.
- Cleanup code in finally blocks runs while unwinding.
Where it is used
Division by zero, missing dictionary keys, failed I/O, invalid arguments and violated preconditions are signaled with exceptions. Custom exception types express domain failures such as InsufficientFunds.
Common pitfall
Using exceptions for ordinary control flow is slow and confusing. Catching Exception broadly hides bugs, and an empty catch block silently loses errors. Throwing from destructors or cleanup code can mask the original failure. Catch only what you can actually handle and preserve the original cause when rethrowing.
Where it fits in the course
Exceptions is topic 29 of 54 in Programming Fundamentals, rated Intermediate. It follows Error Handling. The next topic is File Handling.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Exceptions?
Where do people use Exceptions?
What is the most common mistake with Exceptions?
What should I learn before this topic?
How can I practice it?
Is Exceptions hard to learn?
How long does it take to learn Exceptions?
Which topics are related to Exceptions?
What should I study after Exceptions?
Related topics
- Error Handling (Programming Fundamentals)
- File Handling (Programming Fundamentals)
- Mutability (Programming Fundamentals)
- Modules and Packages (Programming Fundamentals)