PyForge ยท Python practice library
All topics

Topic 12 of 17

Exception Handling

Handle errors gracefully with try / except / finally and custom exceptions.

try/except
else & finally
raise
Custom exceptions

Basic

1 program

Program 1

Basic try/except

Basic

Catch a ZeroDivisionError.

python
try:
    x = 10 / 0
except ZeroDivisionError as e:
    print("Oops:", e)

Intermediate

2 programs

Program 1

Multiple exceptions

Intermediate

Handle different errors differently.

python
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

finally block

Intermediate

Run cleanup code no matter what.

python
try:
    f = open("notes.txt")
    print(f.readline())
except FileNotFoundError:
    print("Missing file")
finally:
    print("Done")

Advanced

1 program

Program 1

Custom exception

Advanced

Define your own exception class.

python
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)