Understanding Error and Exception Handling in Python
Errors and exceptions are inevitable in programming. Python provides a robust framework to handle them gracefully, ensuring your program can recover from unexpected conditions and continue running smoothly.
1. What are Errors and Exceptions?
- Errors: Issues in the syntax or logic that prevent the program from running.
Example:SyntaxError
,IndentationError
. - Exceptions: Errors detected during execution, which can be handled.
Example:ValueError
,ZeroDivisionError
.
2. Common Types of Exceptions
Here are some frequently encountered exceptions in Python:
- SyntaxError: Occurs when there is an issue with the program’s syntax.
Example:if True print("Hello") # SyntaxError: missing colon
- ZeroDivisionError: Occurs when dividing by zero.
Example:print(10 / 0) # ZeroDivisionError
- ValueError: Raised when an operation receives an invalid argument.
Example:int("abc") # ValueError: invalid literal for int()
- TypeError: Raised when an operation is performed on incompatible types.
Example:"5" + 5 # TypeError: can't concatenate str and int
- KeyError: Raised when accessing a non-existent key in a dictionary.
Example:data = {"name": "Alice"} print(data["age"]) # KeyError: 'age'
3. The try
and except
Block
The try
and except
block is used to catch and handle exceptions.
Basic Syntax:
try:
# Code that might raise an exception
risky_operation()
except ExceptionType:
# Code to handle the exception
handle_error()
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input. Please enter a number.")
4. The else
and finally
Clauses
else
: Executes if no exception is raised in thetry
block.finally
: Executes regardless of whether an exception occurs, often used for cleanup.
Example:
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
else:
print("File content:", content)
finally:
file.close()
print("File closed.")
5. Raising Exceptions
You can explicitly raise exceptions using the raise
statement.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above.")
print("Access granted.")
try:
check_age(15)
except ValueError as e:
print("Error:", e)
6. Creating Custom Exceptions
Python allows you to define custom exceptions for specific use cases.
Example:
class InvalidInputError(Exception):
pass
def process_input(data):
if not isinstance(data, int):
raise InvalidInputError("Input must be an integer.")
print("Processing:", data)
try:
process_input("abc")
except InvalidInputError as e:
print("Custom Exception:", e)
7. Best Practices for Exception Handling
- Be Specific with Exceptions: Catch only the exceptions you expect.
# Bad practice: Catching all exceptions except Exception: pass
- Use
finally
for Cleanup: Always close files, release resources, or rollback transactions in thefinally
block. - Avoid Silent Failures: Never suppress exceptions without logging or handling them.
# Bad practice try: risky_operation() except Exception: pass # No action
- Log Errors: Use logging libraries to record errors for debugging.
- Rethrow Exceptions: If you can’t handle an exception, let it propagate.
try: risky_operation() except SpecificError: raise
8. Real-World Use Case: API Request Handling
When working with external APIs, exception handling is crucial for dealing with issues like connection errors or invalid responses.
Example:
import requests
try:
response = requests.get("https://api.example.com/data")
response.raise_for_status() # Raises HTTPError for bad responses
data = response.json()
except requests.exceptions.RequestException as e:
print("API request failed:", e)
else:
print("Data received:", data)
Conclusion
Proper error and exception handling is a hallmark of robust and professional code. By anticipating and managing exceptions effectively, you can ensure your Python applications are reliable and user-friendly.