Exception Handling
 Introduction to Exceptions
Imagine you are following a recipe to bake a cake. Everything goes smoothlyâuntil you accidentally drop the eggs on the floor. What do you do? You handle the problem, maybe by getting fresh eggs, instead of stopping your cooking entirely.
In programming, similar âunexpected problemsâ can happen. These problems are called exceptions.
What is an Exception?
An exception is an event that disrupts the normal flow of a program. It is usually caused by errors, such as:
-
Dividing a number by zero.
-
Trying to open a file that doesnât exist.
-
Accessing a list element that is out of range.
For example, in Python:
Without handling it, the program will stop immediately and show an error message, which is not ideal for user-friendly applications.
Why Handle Exceptions?
-
Prevent program crashes: Users wonât see ugly error messages.
-
Allow recovery: Programs can try an alternative plan if something goes wrong.
-
Debugging: Exception messages help identify issues during development.
Page 2: How Exception Handling Works
Most programming languages provide a structured way to handle exceptions, usually through try, catch (or except), and sometimes finally.
Basic Syntax in Python
Explanation:
-
try block: Code that might cause an exception goes here.
-
except block: Code that executes if a specific exception occurs.
-
finally block (optional): Code that always runs, whether there was an exception or not. Useful for closing files or releasing resources.
Output example:
Even though there was an error, the program did not crash.
Types of Exceptions
Some common built-in exceptions in Python:
| Exception Name | Cause |
|---|---|
ZeroDivisionError |
Dividing a number by zero |
ValueError |
Invalid input type (e.g., string instead of number) |
IndexError |
Accessing a list or array out of bounds |
FileNotFoundError |
Trying to open a file that doesnât exist |
TypeError |
Performing an operation on incompatible types |
Tip: You can also create custom exceptions for your specific program errors.
Page 3: Advanced Exception Handling Concepts
Multiple Exceptions in One Block
You can handle multiple exceptions in one except:
-
Using
as eallows you to capture the error message for logging or debugging.
Raising Exceptions
Sometimes you want to intentionally trigger an exception if something unexpected happens:
-
raiseallows you to signal that something is wrong, which can be caught later.
Best Practices
-
Catch specific exceptions instead of a general one.
-
â
except ZeroDivisionError: -
â
except:(too broad)
-
-
Clean up resources using
finallyorwith(context managers in Python). -
Donât ignore exceptions silently â always log or handle them meaningfully.
Page 4: Real-Life Analogy and Examples
Analogy: Traffic Control
Think of a program as a car driving on a road:
-
A normal road = normal code execution.
-
Unexpected potholes or accidents = exceptions.
-
Traffic signals and safety barriers = exception handling that ensures the car reaches its destination safely.
Example: Reading a File Safely
-
Even if the file is missing, the program wonât crash.
-
The
finallyblock ensures the file is always closed.
Summary
-
Exceptions are errors that disrupt normal program flow.
-
Exception handling ensures your program runs smoothly even when errors occur.
-
Key tools:
-
tryâ code that may fail -
exceptâ handle the error -
finallyâ run cleanup code -
raiseâ trigger custom errors
-
-
Following best practices improves reliability, debugging, and user experience.