Error and Exception Handling
Error and Exception Handling
Types of Errors
1. try and except: The try block contains code that might
throw an exception, and the except block contains code to
handle the exception.
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Handling the exception
print("Cannot divide by zero!")
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
Catching Multiple Exceptions
try:
# Code that may raise different types of exceptions
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
try:
num = int(input("Enter a number: "))
result = 10 / num
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
Raising Exceptions
You can raise exceptions using the raise statement. This is useful
for generating custom exceptions.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age
try:
check_age(-1)
except ValueError as e:
print(e)