Exception handling in Python allows you to gracefully manage errors that might occur during program execution. This prevents your program from crashing.
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero")
The `try` block contains the code that might raise an exception. The `except` block catches the `ZeroDivisionError` and handles it appropriately.
try:
result = int("abc") # This will raise a ValueError
except ZeroDivisionError:
print("Error: Division by zero")
except ValueError:
print("Error: Invalid input")
This shows how to handle different types of exceptions using multiple `except` blocks.
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Division by zero")
else:
print("Result:", result) # Executed if no exception occurs
The `else` block is executed only if no exception occurs in the `try` block.
try:
file = open("my_file.txt", "r")
except FileNotFoundError:
print("Error: File not found")
finally:
try:
if 'file' in locals() and file:
file.close()
except NameError:
print("No file to close")
The `finally` block is always executed, regardless of whether an exception occurred or not. It's useful for cleanup operations (closing files, releasing resources, etc.). The example now includes a `try...except` block within the `finally` to gracefully handle the case where a file object may not exist.
class InvalidAgeError(Exception):
pass
def check_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative")
elif age > 120:
raise InvalidAgeError("Age seems too high")
else:
print("Valid age")
try:
check_age(-5)
except InvalidAgeError as e:
print(f"Error: {e}")