NotesPythonErrors & Files

Exception Handling

try/except/else/finally — handling things going wrong without crashing the program.

When Python hits an error it can't recover from on its own, it raises an exception — if nothing catches it, the program crashes and prints a traceback. try/except lets you catch specific exceptions and decide what to do instead of crashing.

try:
    age = int(input("Enter your age: "))
    print(f"Next year you'll be {age + 1}")
except ValueError:
    print("That's not a valid number")

Catching specific exceptions

Always catch the most specific exception type you can — a bare except: catches everything, including typos and KeyboardInterrupt, which usually hides real bugs instead of handling them.

data = {"CodeWithMunnaX": 250_000}

try:
    print(data["CodeWithHarry"])
except KeyError:
    print("Channel not found")
except TypeError:
    print("Keys must be hashable")

You can catch multiple exception types in one clause with a tuple: except (KeyError, TypeError):.

else and finally

  • else runs only if the try block didn't raise anything.
  • finally always runs, whether an exception happened or not — used for cleanup (closing a file, releasing a resource).
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Can't divide by zero")
else:
    print("No error, result is", result)
finally:
    print("This always runs")

Raising your own exceptions

Use raise to signal that something is wrong in your own code — often paired with a custom, descriptive message.

def subscribe(subscriber_count):
    if subscriber_count < 0:
        raise ValueError("Subscriber count can't be negative")
    return subscriber_count + 1

try:
    subscribe(-5)
except ValueError as e:
    print("Rejected:", e)

Common built-in exceptions

ExceptionWhen it happens
ValueErrorRight type, wrong value (int("abc"))
TypeErrorOperation on the wrong type ("2" + 2)
KeyErrorMissing dict key
IndexErrorList index out of range
ZeroDivisionErrorDividing by zero
FileNotFoundErrorOpening a file that doesn't exist
Key points to remember
  • try/except catches exceptions so your program can handle them instead of crashing with a traceback.
  • Catch the most specific exception type you can — a bare except: hides real bugs, including typos.
  • else runs only if the try block succeeded; finally always runs, success or failure — used for cleanup.
  • raise ValueError('message') is how you signal an error condition from your own code.
  • except Exception as e: lets you access the exception object itself, e.g. to print its message.

try/except/else/finally end to end

Revision Flashcards

1 / 3

Tap a card to flip it and see the answer.