Chapter 9: Error and Exception Handling
Errors and exceptions are inevitable in programming. Python provides a robust mechanism for handling errors gracefully to ensure programs can recover and continue execution where possible.
Types of Errors
Syntax Errors:
Occur when the code violates Python’s grammar rules.
Example:
print("Hello") # Correct print("Hello" # SyntaxError: unexpected EOF while parsing
Runtime Errors:
Occur during the execution of a program.
Example:
result = 10 / 0 # ZeroDivisionError
Logical Errors:
Errors in the program’s logic that produce incorrect results without causing crashes.
Example:
# Intended to calculate the average total = 100 count = 0 average = total / count # ZeroDivisionError
Handling Exceptions
Python uses try...except blocks to handle exceptions.
Syntax:
Example:
The else Clause
else ClauseThe else block executes if no exceptions are raised in the try block.
Example:
Raising Exceptions
Use the raise keyword to generate exceptions intentionally.
Example:
Creating Custom Exceptions
You can define your own exceptions by subclassing the built-in Exception class.
Example:
Common Built-in Exceptions
Exception
Description
ValueError
Raised when a function receives an invalid argument.
TypeError
Raised when an operation is performed on an inappropriate type.
ZeroDivisionError
Raised when dividing by zero.
KeyError
Raised when a key is not found in a dictionary.
IndexError
Raised when an index is out of range.
FileNotFoundError
Raised when a file operation fails because the file doesn’t exist.
Example:
Logging Exceptions
Use the logging module to record errors and exceptions for debugging and analysis.
Example:
Exercises
Exercise 1:
Write a program to take two numbers as input and perform division. Handle ZeroDivisionError and ValueError exceptions.
Solution:
Exercise 2:
Create a custom exception OutOfRangeError that is raised when a number is not between 1 and 100.
Solution:
Exercise 3:
Write a program that logs errors to a file instead of printing them to the console.
Solution:
Best Practices
Use specific exception types instead of a generic
exceptclause.Keep the
tryblock small and focused.Log exceptions for debugging and maintenance.
Avoid using exceptions for normal control flow.
Use custom exceptions to represent specific error cases in your application.
In the next chapter, we will explore working with databases using Python, including basic CRUD operations and interacting with sqlite3.
Last updated