Program 1
Basic try/except
Catch a ZeroDivisionError.
python
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Oops:", e)Topic 12 of 17
Handle errors gracefully with try / except / finally and custom exceptions.
Program 1
Catch a ZeroDivisionError.
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Oops:", e)Program 1
Handle different errors differently.
def parse(value):
try:
return int(value)
except ValueError:
return None
except TypeError:
return 0
print(parse("42"))
print(parse("abc"))
print(parse(None))Program 2
Run cleanup code no matter what.
try:
f = open("notes.txt")
print(f.readline())
except FileNotFoundError:
print("Missing file")
finally:
print("Done")Program 1
Define your own exception class.
class NegativeAgeError(Exception):
pass
def set_age(age):
if age < 0:
raise NegativeAgeError("Age cannot be negative")
return age
try:
set_age(-5)
except NegativeAgeError as e:
print(e)