Welcome to the exciting world of error handling in Python! While writing code, you'll inevitably encounter situations where things don't go as planned. These unexpected hiccups are called exceptions. Python provides a powerful mechanism to gracefully handle these exceptions, preventing your program from crashing and allowing you to manage errors in a structured way. This is where the try and except block comes into play.
The try block is where you place the code that you suspect might raise an exception. Python will execute this code. If an exception occurs within the try block, Python will immediately stop executing the rest of the code in the try block and look for a matching except block to handle the error.
try:
# Code that might cause an error
result = 10 / 0
print(result)The except block is where you define how to respond to a specific type of exception. If an exception occurs in the try block, Python checks if there's an except block that matches the type of exception that was raised. If a match is found, the code within that except block is executed. This allows you to provide informative messages to the user, log the error, or attempt to recover from the error.
try:
result = 10 / 0
print(result)
except ZeroDivisionError:
print('Error: Cannot divide by zero!')In the example above, dividing by zero raises a ZeroDivisionError. The except ZeroDivisionError: block catches this specific error and prints a user-friendly message instead of crashing the program. You can have multiple except blocks to handle different types of exceptions.
graph TD;
Start --> TryBlock{Try Block};
TryBlock --> CodePotentialError{Code that might raise an exception};
CodePotentialError -- Exception Occurs --> ExceptBlock{Except Block};
ExceptBlock --> HandleError[Handle the error gracefully];
CodePotentialError -- No Exception --> End[Program continues normally];
It's a good practice to be as specific as possible with your except blocks. Catching a general Exception can hide other unexpected errors. By catching specific exceptions like ValueError, TypeError, or ZeroDivisionError, you gain better control and understanding of what went wrong.
try:
user_input = input('Enter a number: ')
number = int(user_input)
result = 10 / number
print(f'The result is: {result}')
except ValueError:
print('Invalid input. Please enter a valid integer.')
except ZeroDivisionError:
print('Error: Cannot divide by zero. Please enter a non-zero number.')The else clause can be added to the try...except block. The code within the else block will only execute if the try block completes successfully without raising any exceptions. This is useful for code that should run only when no errors occurred.
try:
number = int(input('Enter a number: '))
result = 10 / number
except ValueError:
print('Invalid input. Please enter a valid integer.')
except ZeroDivisionError:
print('Error: Cannot divide by zero.')
else:
print(f'Calculation successful. The result is: {result}')Finally, the finally clause is executed regardless of whether an exception occurred or not. This is often used for cleanup operations, such as closing files or releasing resources, ensuring that these actions always take place.
file = None
try:
file = open('my_file.txt', 'r')
content = file.read()
print(content)
except FileNotFoundError:
print('Error: The file was not found.')
finally:
if file:
file.close()
print('File has been closed.')