Chapter 9: Error Handling and Debugging
Understand Python�s error handling mechanisms and learn debugging techniques to identify and fix issues in your code.
In this chapter, we�ll explore Python�s error handling features, including using try
, except
, and other statements to manage exceptions gracefully. Additionally, we�ll discuss debugging techniques to help you identify and fix issues in your code.
Types of Errors in Python
Errors in Python can be broadly classified into two categories:
- Syntax Errors: Occur when Python cannot interpret a line of code, often due to a typo or incorrect syntax.
- Exceptions: Occur when an error is detected during program execution, such as dividing by zero or referencing a missing variable.
Using try
and except
Blocks
Python�s try
and except
blocks allow you to catch and handle exceptions, preventing the program from crashing:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
In this example, the ZeroDivisionError
is caught, and a friendly message is printed instead of the program crashing.
Catching Multiple Exceptions
You can catch multiple exceptions by specifying multiple except
blocks or using a tuple of exception types:
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
In this example, different error messages are displayed depending on the type of exception that occurs.
Using finally
for Cleanup
The finally
block is executed after try
and except
blocks, regardless of whether an exception occurred. It�s useful for releasing resources like closing files or database connections:
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
In this example, file.close()
is guaranteed to run, even if an exception is raised, ensuring that resources are properly released.
Debugging Techniques
Debugging involves identifying and fixing errors in your code. Here are some common techniques:
- Print Statements: Use
print()
to display variable values and track code execution. - Using the Debugger: Most IDEs, such as PyCharm and VS Code, have built-in debuggers that allow you to set breakpoints and inspect variables.
- Reading Tracebacks: Python�s error messages (tracebacks) show where an error occurred, which helps in pinpointing issues.
# Example of using print statements for debugging
def add_numbers(a, b):
print("a:", a, "b:", b) # Debugging print
return a + b
result = add_numbers(10, "20") # Causes a TypeError
In this example, a print
statement helps identify that one of the arguments is a string, leading to a TypeError
.
Raising Exceptions
In some cases, you may want to raise exceptions intentionally to handle errors more effectively. Use the raise
keyword to do this:
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
In this example, ValueError
is raised if the divisor b
is zero, providing a custom error message.
Summary and Next Steps
In this chapter, we covered Python�s error handling mechanisms, including try
, except
, and finally
, as well as useful debugging techniques. Error handling and debugging are essential skills for writing robust code. In the next chapter, we�ll explore how to work with APIs and handle JSON data in Python.