Errors handling
Exceptions are events that occur during the execution of a program that disrupt the normal flow of code. They typically arise due to errors in the code or external factors like invalid user input or system failures. Python provides a robust mechanism for handling exceptions using the "try", "except", and "finally" blocks.
- 1. "try", "except", and "finally" Blocks:
- 2. Handling Exceptions with try and except:
The "try" block is used to enclose the code that might raise an exception. The "except" block is used to handle specific exceptions that might occur in the "try" block. The "finally" block is used to specify code that should be executed regardless of whether an exception occurred.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
print("Division by zero error occurred.")
In this example, the code within the "try" block attempts to perform a division by zero, which would raise a "ZeroDivisionError". The "except" block catches this exception and prints an error message.
You can use multiple except blocks to handle different types of exceptions.
try:
# Code that might raise exceptions
value = int("not_an_integer")
except ValueError:
print("ValueError occurred: Invalid conversion.")
except ZeroDivisionError:
print("ZeroDivisionError occurred: Division by zero.")
You can use a generic except block without specifying the exception type to catch all exceptions. However, it's generally recommended to catch specific exceptions whenever possible to handle errors more precisely.
try:
# Code that might raise an exception
result = 10 / 0
except Exception as e:
print(f"An exception occurred: {e}")
You can use the "else" block after the "except" block to specify code that should run if no exceptions occur.
try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError:
print("Division by zero error occurred.")
else:
print("No exceptions occurred.")
The "finally" block is used to define code that should be executed regardless of whether an exception occurred.
try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError:
print("Division by zero error occurred.")
finally:
print("Cleanup code: This will always be executed.")
The "finally" block is often used for cleanup tasks like closing files or releasing resources.
You can manually raise exceptions using the "raise" statement. This can be useful when you want to handle specific conditions.
try:
x = -1
if x < 0:
raise ValueError("Negative value not allowed.")
except ValueError as e:
print(f"An exception occurred: {e}")
Python's exception handling mechanism allows you to gracefully handle errors and exceptions, making your code more robust and user-friendly. By using "try", "except", and "finally" blocks, you can control the behavior of your program when exceptions occur and ensure that necessary cleanup operations are performed.