In Python, exceptions are errors that occur during program execution. Instead of crashing the program, Python allows you to handle these errors gracefully using exception handling.
🔹 What is Exception Handling in Python?
Exception handling is:
A mechanism to handle runtime errors so that the program continues to run smoothly instead of stopping unexpectedly.
In simple words:
- Error happens → program normally crashes ❌
- Exception handling → program handles error and continues ✅
🔹 Why Do We Need Exception Handling?
We use exception handling to:
- ✔ Prevent program crashes
- ✔ Improve user experience
- ✔ Handle unexpected situations
- ✔ Debug errors easily
- ✔ Make applications more stable
🔹 Basic Syntax of Exception Handling
try:
# risky code
pass
except:
# handle error
pass
🔹 Simple Example of Exception Handling
try:
x = 10 / 0
except:
print("Something went wrong!")
Output:
Something went wrong!
👉 Program did NOT crash
🔹 Types of Errors (Exceptions)
Common Python exceptions:
| Exception | Meaning |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Wrong value type |
| TypeError | Wrong data type operation |
| IndexError | Invalid list index |
| KeyError | Invalid dictionary key |
| NameError | Variable not defined |
🔹 1. Handling Specific Exceptions
try:
x = int("abc")
except ValueError:
print("Invalid value provided")
Output:
Invalid value provided
🔹 2. Multiple Exception Handling
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid value")
🔹 3. Using else Block
The else block runs if no error occurs.
try:
x = 10 / 2
except ZeroDivisionError:
print("Error occurred")
else:
print("No error, result is", x)
Output:
No error, result is 5.0
🔹 4. Using finally Block
The finally block always runs.
try:
x = 10 / 0
except ZeroDivisionError:
print("Error handled")
finally:
print("This always executes")
Output:
Error handled
This always executes
🔹 Full Structure of Exception Handling
try:
# risky code
pass
except:
# handle error
pass
else:
# runs if no error
pass
finally:
# always runs
pass
🔹 Real-Life Example (File Handling)
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
print("Execution completed")
🔹 Output (if file missing):
File not found!
Execution completed
🔹 Raising Exceptions Manually
You can create your own errors using raise.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
🔹 Output:
ValueError: Age cannot be negative
🔹 Custom Exception Example
class MyError(Exception):
pass
try:
raise MyError("Custom error occurred")
except MyError as e:
print(e)
🔹 Output:
Custom error occurred
🔹 Difference Between Error and Exception
| Feature | Error | Exception |
|---|---|---|
| Severity | High | Medium |
| Recovery | Not possible | Possible |
| Handling | Not handled | Handled using try-except |
| Example | SyntaxError | ZeroDivisionError |
🔹 Benefits of Exception Handling
✅ 1. Prevents crashes
Program continues running safely.
✅ 2. Better user experience
Shows friendly messages.
��� 3. Easier debugging
Helps identify problems.
✅ 4. Professional code quality
Used in all real-world applications.
🔹 Common Mistakes
❌ Using empty except block:
except:
pass
❌ Not specifying exception type
❌ Ignoring error messages
🔹 Best Practices
✔ Always catch specific exceptions
✔ Use finally for cleanup
✔ Avoid empty except blocks
✔ Log errors properly
🚀 Conclusion
Python exception handling is essential for writing safe, stable, and professional applications. It allows your program to handle unexpected errors without crashing.
By mastering:
- try
- except
- else
- finally
You can build robust real-world applications like:
- Web apps
- APIs
- Automation tools
- Data systems


0 Comments