Python - Exception Handling
What is Exception Handling?
Exception handling in Python is a mechanism that allows you to manage runtime errors gracefully using try, except, finally, and raise. It helps prevent programs from crashing abruptly and allows recovery from unexpected conditions.
Why Use Exception Handling?
- To prevent application crashes due to runtime errors
- To handle user input errors, file errors, network errors, etc.
- To ensure resources (like files or connections) are released properly
Basic try-except Block
python
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!") Handling Multiple Exceptions
python
try:
num = int("abc")
except ValueError:
print("Invalid number format.")
except TypeError:
print("Type error occurred.") Using finally Block
The finally block is always executed, whether or not an exception occurs.
python
try:
f = open("sample.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Executing finally block.")
f.close() Using the raise Keyword
You can raise exceptions manually using raise.
python
age = -1
if age < 0:
raise ValueError("Age cannot be negative") Custom Exceptions
You can create your own exception classes by inheriting from the built-in Exception class.
python
class NegativeNumberError(Exception):
pass
def check_number(n):
if n < 0:
raise NegativeNumberError("Negative numbers are not allowed")
return n
try:
check_number(-5)
except NegativeNumberError as e:
print("Caught custom exception:", e) Best Practices
- Catch specific exceptions instead of using a generic
except - Use
finallyto release resources - Avoid using exceptions for control flow logic
- Document custom exceptions clearly
Conclusion
Exception handling is vital for building robust and user-friendly Python applications. Mastering try-except-finally and custom exceptions ensures your code handles unexpected issues gracefully.