11 Python try and except statements
- Learn what try and except statements do and how to use them
- Learn the syntax and add them to your repertoir of python constructs to deal with unforseen errors
11.1 try and except in Python
In Python, try and except blocks are used for handling exceptions, which are errors that can occur during program execution. This mechanism allows developers to anticipate potential errors, provide alternate code to handle them, and prevent the program from crashing. Here’s how it works:
try Block:
The code that might raise an exception is placed inside the try block. If an exception occurs during execution of this block, the rest of the block is skipped, and control is passed to the except block.
except Block:
This block contains code that handles the exception. You can specify which exception to catch, or leave it blank to catch any exception. If the exception type matches the one specified in the except block, the code inside it is executed.
Multiple except Blocks:
You can have multiple except blocks to handle different types of exceptions.
else Block:
You can add an else block after the except block. This block runs if the try block executes without raising an exception.
finally Block:
The finally block runs regardless of whether an exception was raised or not. It is often used for cleanup actions, like closing files or releasing resources.
Example
Here’s a simple example demonstrating the use of try and except:
try:
# Code that may raise an exception
numerator = 10
denominator = 0
result = numerator / denominator
except ZeroDivisionError:
# Handling a specific exception
print("Error: You cannot divide by zero.")
except Exception as e:
# Handling any other exception
print(f"An unexpected error occurred: {e}")
else:
# Executes if no exception occurred
print("The result is:", result)
finally:
# This block runs no matter what
print("Execution completed.")Explanation of the Example:
try:
- Attempts to divide
numeratorbydenominator. Sincedenominatoris zero, this raises aZeroDivisionError.
except:
- The first
exceptcatches theZeroDivisionErrorand prints an error message. - The second
exceptwould catch any other unexpected exceptions, but it won’t run in this case because the firstexcepthandles the error.
else:
- If there were no exceptions, the
elseblock would print the result.
finally:
- This block runs at the end of the
try/exceptstructure, regardless of whether an exception occurred or not. It’s useful for cleanup actions.
In this case I might not use the else or finally
Benefits of Using try and except:
- Prevents Crashes: By handling exceptions, you can prevent your program from crashing due to unforeseen errors.
- Cleaner Code: It allows for clearer separation of normal code and error handling.
- More Robust Programs: By anticipating and handling potential errors, your programs can handle unexpected situations better.
11.2 Summary
- Python try except statements catch errors and enable code to continue despite some errors
- They are simple to add to scripts where this is important