- Learning Objectives
- Prerequisites
- Introduction
- What is an Exception?
- Why is Exception Handling Required?
- Error vs Exception
- Types of Errors
- Types of Exceptions
- Exception Hierarchy
- Exception Handling Flow
- Internal Working
- Summary
After completing this chapter, you will be able to:
- Understand Exception Handling.
- Differentiate Errors and Exceptions.
- Learn why Exception Handling is important.
- Understand Python's Exception Hierarchy.
- Identify different types of Exceptions.
- Understand the flow of Exception Handling.
Before learning this chapter, you should know:
- Variables
- Operators
- Functions
- Classes
- Objects
- Control Statements
While developing software,
errors may occur during program execution.
Some errors terminate the program immediately.
Consider the following example.
number = 10
result = number / 0
print(result)Output
ZeroDivisionError:
division by zero
The program terminates because Python cannot divide a number by zero.
Instead of allowing the program to terminate unexpectedly,
Python provides Exception Handling.
Exception Handling allows us to detect errors and continue program execution gracefully.
An Exception is an abnormal event that occurs during the execution of a program and interrupts the normal flow of execution.
When an exception occurs,
Python creates an Exception Object and searches for code that can handle it.
An Exception is a runtime event that disrupts the normal execution of a program.
Suppose we are developing an ATM Application.
The customer enters
Withdraw Amount
↓
1000
Current Balance
500
Without Exception Handling,
the application may terminate unexpectedly.
With Exception Handling,
the application displays
Insufficient Balance
and continues execution.
This improves user experience.
Exception Handling is used in:
- ATM Machines
- Banking Applications
- Online Shopping
- Login Systems
- Hospital Management
- Airline Reservation Systems
- Payment Gateways
- Database Applications
| Error | Exception |
|---|---|
| Serious problem | Recoverable problem |
| Difficult to handle | Can be handled |
| Program may terminate | Program can continue |
| Example: Syntax Error | Example: ZeroDivisionError |
Errors are mainly classified into two categories.
Syntax Errors occur when Python rules are violated.
Example
if True
print("Hello")Output
SyntaxError
The program does not execute.
Runtime Errors occur while the program is executing.
Example
print(10 / 0)Output
ZeroDivisionError
Some commonly used exceptions are:
| Exception | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| NameError | Variable not found |
| TypeError | Invalid data type operation |
| ValueError | Invalid value |
| IndexError | Invalid list index |
| KeyError | Dictionary key not found |
| AttributeError | Invalid object attribute |
| FileNotFoundError | File does not exist |
| ImportError | Module cannot be imported |
| ModuleNotFoundError | Module not found |
Python organizes exceptions into a hierarchy.
BaseException
│
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
│
├── ArithmeticError
│ ├── ZeroDivisionError
│ ├── OverflowError
│ └── FloatingPointError
│
├── LookupError
│ ├── IndexError
│ └── KeyError
│
├── TypeError
├── ValueError
├── NameError
├── AttributeError
├── FileNotFoundError
├── ImportError
└── RuntimeError
Most user programs handle exceptions derived from
Exception
When an exception occurs,
Python follows this sequence.
Program Starts
↓
Statements Execute
↓
Exception Occurs?
↓
No
↓
Continue Execution
↓
Program Ends
----------------------------
Yes
↓
Create Exception Object
↓
Search for Matching Handler
↓
Handler Found?
↓
Yes
↓
Execute Handler
↓
Continue Program
----------------------------
No
↓
Program Terminates
Statement Executes
↓
Exception Raised
↓
Python Creates Exception Object
↓
Searches for Matching except Block
↓
Handler Found?
↓
Yes
↓
Execute Handler
↓
Continue Execution
----------------------
No
↓
Program Terminates
- Prevents abnormal program termination.
- Improves software reliability.
- Improves user experience.
- Makes debugging easier.
- Separates error-handling logic from business logic.
- Produces maintainable applications.
- Handle only expected exceptions.
- Keep exception handling simple.
- Display meaningful error messages.
- Avoid suppressing exceptions unnecessarily.
- Use specific exception classes instead of generic ones.
Confusing Errors and Exceptions.
- Syntax Errors occur before execution.
- Exceptions occur during execution.
Ignoring possible runtime exceptions.
Programs should anticipate common runtime failures.
Using overly broad exception handling.
Avoid handling every exception with a generic handler unless necessary.
An Exception is an abnormal event that occurs during program execution and interrupts the normal flow of the program.
It prevents abnormal program termination and allows programs to recover gracefully from runtime problems.
Errors usually indicate serious problems such as syntax issues, while Exceptions are runtime events that can often be handled.
Exception- ZeroDivisionError
- ValueError
- TypeError
- IndexError
- KeyError
- NameError
- AttributeError
- FileNotFoundError
- Exception → Runtime abnormal event
- Syntax Error → Before execution
- Runtime Error → During execution
- Exception Handling prevents program termination
- Python creates an Exception Object
- Searches for a matching handler
- Executes handler if found
In this chapter, we learned:
- Exception Handling
- Errors vs Exceptions
- Syntax Errors
- Runtime Errors
- Exception Hierarchy
- Exception Handling Flow
- Internal Working
- Advantages
- Best Practices
- Common Mistakes
- Interview Questions
- Quick Revision