Welcome to the lesson on Try-Except Blocks in Python! This topic is crucial as it allows you to handle errors and exceptions in your code gracefully. By the end of this lesson, you'll be able to:
Try-Except Blocks are used in Python to catch and handle exceptions or errors that might occur during the execution of your code. The basic structure consists of a try
block, where you place the code that might raise an exception, and one or more except
blocks for catching and handling those exceptions.
Here's the syntax:
try:
# Code that may raise an exception
except ExceptionType: # Replace with specific exception type if known
# Code to handle the exception
Let's look at a simple example where we try to open a non-existent file and catch the FileNotFoundError
.
try:
with open('non_existing_file.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("The specified file does not exist.")
else: # This block executes if no exceptions were raised
print(content)
What causes it: A variable is used but has not been defined yet.
print(undefined_var) # Undefined variable
Error message:
Traceback (most recent call last):
File "example.py", line 5, in <module>
print(undefined_var)
NameError: name 'undefined_var' is not defined
Solution: Define the variable before using it.
undefined_var = None # Initialize the variable
print(undefined_var) # Now it will print None instead of raising an error
Why it happens: Variables must be defined before they can be used.
How to prevent it: Always define variables before using them in your code.
What causes it: Attempting to perform an operation on objects that are not of the expected type.
a = 5
b = "5"
print(a + b) # Concatenating an integer and a string
Error message:
Traceback (most recent call last):
File "example.py", line 4, in <module>
print(a + b)
TypeError: cannot concatenate 'int' and 'str' objects
Solution: Convert one of the operands to a compatible type before performing the operation.
print(str(a) + b) # Now it will concatenate the string properly
Why it happens: Different types have different built-in methods and cannot always be used interchangeably.
How to prevent it: Be aware of the data types you are working with, and ensure they are compatible when performing operations.
Exception
for better error handling.else
clause to check if the code executed successfully without raising any exceptions.else
clause to check if the code executed successfully.