⭐ Exception Handling in Python – Introduction to Exceptions
When a program runs, it may face unexpected situations such as:
- A file not found
- Dividing a number by zero
- Wrong input type
- Accessing an undefined variable
- Out-of-range index
These situations cause the program to stop suddenly with an error message.
Such runtime errors are called Exceptions.
⭐ What is an Exception? (Exam Definition)
An exception is an error that occurs during the execution of a program, which disrupts the normal flow of instructions.
Python stops the program and displays an error message.
Exceptions are not syntax errors; they occur at runtime.
⭐ Examples of Common Exceptions
| Exception | When it occurs |
|---|---|
ZeroDivisionError | When dividing by zero |
TypeError | Wrong data type used |
NameError | Using an undefined variable |
IndexError | Accessing index out of range |
ValueError | Wrong value given |
FileNotFoundError | File does not exist |
KeyError | Key not found in dictionary |
ImportError | Module not found |
⭐ Example of an Exception
Example 1: Division by Zero
a = 10
b = 0
print(a / b)
Output:
ZeroDivisionError: division by zero
Example 2: Invalid Index
lst = [1, 2, 3]
print(lst[5])
Output:
IndexError: list index out of range
⭐ Why Do Exceptions Occur?
Exceptions happen due to:
✔ Invalid operations
✔ Unexpected user input
✔ Missing resources (files, internet, etc.)
✔ Logical mistakes in code
✔ External errors (network failure, hardware issues)
⭐ Impact of Exceptions
If an exception occurs and is not handled, the program will:
❌ Crash
❌ Stop execution
❌ Show error message
In real applications (banking, gaming, web apps), crashes are unacceptable!
⭐ Why Do We Need Exception Handling?
Exception handling is used to:
✔ Prevent sudden program crashes
✔ Provide meaningful error messages
✔ Allow the program to continue execution
✔ Handle predictable runtime mistakes safely
⭐ Normal Flow vs Exception Flow
Normal Flow:
Program executes all statements successfully.
Exception Flow:
If an error occurs:
- Python stops executing
- Throws an exception
- If not handled → program terminates
- If handled → program continues
⭐ Exception Handling Keywords (Overview)
Python provides the following keywords:
| Keyword | Purpose |
|---|---|
try | Code that may cause an exception |
except | Handles the exception |
else | Executes if no exception occurs |
finally | Executes always, clean-up code |
raise | Manually raise an exception |
(We will discuss these in detail later.)
⭐ Simple Example of Handling an Exception
try:
x = 10 / 0
except:
print("Error: Cannot divide by zero!")
Output:
Error: Cannot divide by zero!
Program does not crash — exception is handled safely.
⭐ Benefits of Exception Handling
✔ Graceful handling of errors
✔ Prevents program termination
✔ Provides debugging information
✔ Makes code more reliable and robust
✔ Useful in user-input validation, file handling, networks, databases
⭐ Exam-Ready Definition
An exception is a runtime error that interrupts the normal flow of a program. Exception handling allows the programmer to detect, handle, and recover from such errors using try-except blocks, preventing the program from crashing.
