Learn complete Exception Handling in Python with try, except, else, and finally blocks. Includes raise statement, hierarchy, and user-defined exceptions explained with examples.
Exception Handling in Python — Try, Except, Else, Finally, and Raise Explained
Introduction
Exception Handling in Python is a powerful feature used to handle runtime errors so that a program can continue executing without crashing.
Its main purpose is:
“Catch the error and handle it gracefully.”
Whenever a runtime error occurs, Python stops the normal flow of execution and throws an exception. Exception handling allows developers to respond to such errors and prevent abrupt termination.
Exception Handling Structure in Python
Python provides four main keywords for handling exceptions:
Keyword | Description |
try | Contains the code that might cause an error |
except | Handles the error when it occurs |
else | Executes when no exception occurs |
finally | Executes always (whether error occurs or not) |
-
try Block
This block contains suspicious code — i.e., the part of the code where an error might occur.
Example:
try:
x = int(input(“Enter a number: “))
y = 10 / x
print(“Result:”, y)
-
except Block
This block executes only when an error occurs in the try block.
You can handle multiple exceptions using multiple except statements.
Example:
try:
x = int(input(“Enter a number: “))
y = 10 / x
print(“Result:”, y)
except ZeroDivisionError:
print(“Error: Cannot divide by zero!”)
except ValueError:
print(“Error: Please enter only numbers!”)
-
else Block
If no error occurs in the try block, then the else block runs.
Example:
try:
x = int(input(“Enter a number: “))
y = 10 / x
except ZeroDivisionError:
print(“Error: Cannot divide by zero!”)
else:
print(“Result:”, y)
Note: The else block executes only when the try block runs successfully without errors.
-
finally Block
The finally block always executes — whether an exception occurs or not.
It is commonly used for cleanup operations such as closing files or releasing resources.
Example:
try:
file = open(“data.txt”, “r”)
data = file.read()
print(data)
except FileNotFoundError:
print(“Error: File not found!”)
finally:
print(“File processing finished.”)
Complete Example
try:
num = int(input(“Enter a number: “))
result = 10 / num
except ZeroDivisionError:
print(“Error: Division by 0 is not possible.”)
except ValueError:
print(“Error: Please enter only numbers.”)
else:
print(“Result =”, result)
finally:
print(“Program ended.”)
Output 1 (Valid Input)
Enter a number: 5
Result = 2.0
Program ended.
Output 2 (Zero Input)
Enter a number: 0
Error: Division by 0 is not possible.
Program ended.
Key Points to Remember
Block | When It Executes | Purpose |
try | Code where error might occur | Suspicious code |
except | When error occurs | Handle the error |
else | When no error occurs | Normal execution |
finally | Always executes | Cleanup operations |
The raise Statement — Manually Raising Exceptions
The raise statement is used when you want to intentionally trigger an exception in your code.
Syntax:
raise ExceptionType(“Error Message”)
Example 1:
x = -5
if x < 0:
raise ValueError(“The number should not be negative!”)
Output:
ValueError: The number should not be negative!
Example 2:
try:
age = int(input(“Enter your age: “))
if age < 18:
raise Exception(“Your age is less than 18 years.”)
print(“Welcome!”)
except Exception as e:
print(“Error:”, e)
Output:
Enter your age: 16
Error: Your age is less than 18 years.
Exception Hierarchy in Python
All Python exceptions are derived from the BaseException class.
Text-based Hierarchy Diagram:
BaseException
│
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
├── ArithmeticError
│ ├── ZeroDivisionError
│ └── OverflowError
│
├── LookupError
│ ├── IndexError
│ └── KeyError
│
├── ValueError
├── TypeError
├── FileNotFoundError
├── AttributeError
├── ImportError
└── RuntimeError
Explanation:
- BaseException → Top-most class (root of all exceptions).
- Exception → Most programming errors derive from here.
- ArithmeticError → Mathematical errors like division by zero.
- LookupError → Errors like wrong index or missing key.
Creating Custom (User-Defined) Exceptions
When built-in exceptions are not enough, we can define our own custom exception class. Syntax:
class MyError(Exception):
pass
Example:
class NegativeNumberError(Exception):
“””Negative number not allowed”””
pass
try:
num = int(input(“Enter a positive number: “))
if num < 0:
raise NegativeNumberError(“Negative numbers are not allowed!”)
print(“Number =”, num)
except NegativeNumberError as e:
print(“Custom Exception:”, e)
Output:
Enter a positive number: -5
Custom Exception: Negative numbers are not allowed!
Summary Table
Concept | Description |
raise statement | Used to manually raise an exception |
Exception Hierarchy | BaseException → Exception → Specific Errors |
Custom Exception | class MyError(Exception): pass |
except Exception as e | Used to catch the exception object |
Use Case | When we want to define our own custom error message |
Conclusion
Exception handling makes Python programs more reliable and error-tolerant.
Using try-except-else-finally, programmers can handle errors gracefully, ensuring smooth execution and proper resource management.
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
https://defineinfoloop.blogspot.com/?m=1