Untitled Document (37)
Untitled Document (37)
1. Introduction to Exceptions
Types of Errors:
Example:
import re
year = int(user_input)
else:
Limitations:
Python provides a structured way to handle errors using the try and
except blocks.
Basic Structure:
try:
risky_operation()
except ExceptionType:
# Code to handle the exception
try:
print("Result:", result)
except ZeroDivisionError:
When a block of code may raise different types of exceptions, you can use
multiple except blocks.
Example:
try:
print("Result:", result)
except ZeroDivisionError:
print("Details:", ve)
Key Points:
try:
print("Error:", ve)
Exception Description
logging.basicConfig(filename='error.log',
level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
data = file.read()
except FileNotFoundError:
finally:
file.close()