-
Notifications
You must be signed in to change notification settings - Fork 17
1.4 Error Handling
Error handling in Python is managed using the try, except, else, and finally blocks. This structure allows developers to gracefully handle errors that may occur during runtime, ensuring that the program can either recover from an issue or fail gracefully with useful feedback.
The try block contains code that might raise an error. If an error occurs, the except block is executed, and Python will not terminate the program abruptly. You can catch specific exceptions or handle all exceptions generally.
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")try:
num = int(input("Enter a number: "))
except Exception as e:
print(f"An error occurred: {e}")The else block is optional and runs if no exception was raised in the try block.
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print(f"Success! The result is {result}.")The finally block runs regardless of whether an exception occurred or not. It’s often used for cleanup actions like closing files or database connections.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")Python allows you to raise exceptions using the raise keyword, either with built-in exceptions or custom ones.
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
return True
try:
check_age(16)
except ValueError as e:
print(e)Error handling in Python enables more robust and maintainable code by catching potential issues, allowing graceful recovery, and ensuring proper resource management. You'll use try, except, else, and finally in this week's assignment by... TBD