Error and exception handling is a crucial skill for any Python programmer to ensure that your code can gracefully handle unexpected situations. In this comprehensive guide, we will dive deep into the world of error and exception handling in Python, complete with real-world examples and their outputs.
What are Exceptions?
In Python, an exception is an event that disrupts the normal flow of the program’s execution. These exceptions can occur due to various reasons, such as invalid input, file not found, or even a division by zero. When an exception occurs, Python generates an exception object that contains information about the error, including its type and details.
Handling Exceptions with try
and except
The primary way to handle exceptions in Python is by using the try
and except
blocks. Here’s the basic syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Let’s consider an example where we divide two numbers, but we want to handle the possibility of a ZeroDivisionError
:
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
else:
print("Result:", result)
Output:
Error: Division by zero!
In this example, the code inside the try
block raises a ZeroDivisionError
, and the program jumps to the except
block, printing an error message.
Multiple Exceptions and Generic except
You can also handle multiple exceptions or use a generic except
block to catch any unexpected exceptions:
try:
# Code that might raise an exception
except (ExceptionType1, ExceptionType2) as e:
# Code to handle specific exceptions
except Exception as e:
# Code to handle any other exceptions
The finally
Block
In some cases, you might want to execute code regardless of whether an exception was raised or not. You can achieve this using the finally
block:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
finally:
# Code that always gets executed
Examples
Let’s explore a few real-world examples of exception handling in Python:
Example 1: File Handling
try:
file = open("non_existent_file.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
else:
print("File content:", content)
finally:
file.close()
Output:
File not found!
In this example, we attempt to open a non-existent file, which triggers a FileNotFoundError
. We catch and handle this exception and close the file in the finally
block.
Example 2: User Input
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid input. Please enter a valid age.")
else:
print("Your age is:", age)
In this example, we prompt the user for their age. If they enter a non-integer value, a ValueError
is raised and caught, and an error message is displayed.