Skip to main content

CHAPTER 15: EXCEPTION HANDLING

15.1 TRY-EXCEPT

15.1.1 Basic Structure

<PYTHON>

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

15.1.2 Multiple Exceptions

<PYTHON>

try:
file = open("data.txt", "r")
data = int(file.read())
except FileNotFoundError:
print("File not found")
except ValueError:
print("Invalid number")

15.1.3 Finally Block

<PYTHON>

try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
if 'file' in locals():
file.close()

15.1.4 Raising Exceptions

<PYTHON>

def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b

try:
result = divide(10, 0)
except ValueError as e:
print(e)