basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Errors and exceptions: reading tracebacks and catching only what you expect

    When an operation fails, Python stops the script and prints a traceback — the path to the failing line and the reason. A try/except block catches an expected error so a bad line or missing file doesn’t take down the whole run. Parse a ports file, read tracebacks from bottom to top and see why bare except: is dangerous.

    What you’ll get

    A ports.txt file lists services and ports, but two lines are broken — one writes the port in words, another has no colon:

    ssh:22
    http:eighty
    https:443
    broken-line

    Without error handling, the script crashes on line 2 and never reaches https:443. Wrap line parsing in try/except ValueError to skip bad lines with a message and collect the rest into a dict:

    # parse_ports.py
    from pathlib import Path
    
    ports = {}
    with open(Path("ports.txt"), encoding="utf-8") as f:
        for n, line in enumerate(f, start=1):
            try:
                name, raw_port = line.strip().split(":")
                ports[name] = int(raw_port)
            except ValueError:
                print(f"Line {n} skipped: {line.strip()!r}")
    
    print(ports)
    python parse_ports.py
    # Line 2 skipped: 'http:eighty'
    # Line 4 skipped: 'broken-line'
    # {'ssh': 22, 'https': 443}

    Both failures raise ValueError: on line 2 int("eighty") fails, and on line 4 unpacking one item into two variables name, raw_port fails. One except ValueError covers both cases, while a typo like portss[name] still stops the script right away instead of hiding silently.

    What will it print?
    def to_port(text):
        try:
            return int(text)
        except ValueError:
            return 80
        finally:
            print("checked")
    
    print(to_port("abc"))
    What will it print?
    Answer:
    checked
    80

    finally always runs — even right before exiting on return. So checked prints first, and then the function returns 80 to print.

    How to read a traceback

    When an exception isn’t caught, Python prints a traceback — the chain of calls from the start of the script to the line where execution stopped:

    Traceback (most recent call last):
      File "parse_ports.py", line 10, in <module>
        load_ports()
        ~~~~~~~~~~^^
      File "parse_ports.py", line 6, in load_ports
        return parse_line("http:eighty")
      File "parse_ports.py", line 3, in parse_line
        return name, int(raw_port)
                     ~~~^^^^^^^^^^
    ValueError: invalid literal for int() with base 10: 'eighty'

    Read a traceback from bottom to top:

    • the last line gives the exception type and reason: ValueError, 'eighty' can’t be parsed as an integer;
    • right above it sits the exact failure point, underlined with ~~~^^^: the int(raw_port) call on line 3 of parse_ports.py;
    • higher up are the callers (load_ports on line 6, called from line 10).

    The most common exceptions in everyday scripts:

    Exception When it happens
    ValueError right type, bad value: int("abc"), wrong item count on unpack
    TypeError operation doesn’t fit the type: "10" + 5, calling a number like a function
    KeyError key missing from a dict: ports["ftp"]
    IndexError index past the end of a list or string: items[10]
    FileNotFoundError no file or folder at that path
    ZeroDivisionError division by zero: total / 0
    AttributeError object has no such method or attribute: (1, 2).append(3)

    try, except, else and finally

    Keep only the lines that can raise the expected error inside try. The shorter the try block, the lower the chance of catching something unintended.

    Capture the caught error message with as e. List multiple exception types as a tuple in parentheses:

    try:
        text = Path("config.txt").read_text(encoding="utf-8")
    except (FileNotFoundError, PermissionError) as e:
        print("Could not read file:", e)
    else:
        print("Lines in config:", len(text.splitlines()))
    • else runs only when try finishes with no exception. Put post-processing here so except won’t catch bugs in it.
    • finally runs no matter what — after success, after except, and before return. Use it to release resources or clean up temporary files; for files, prefer with open from Files and paths over a manual finally.

    A bare except: without an exception class is a trap. It catches everything, including typos (NameError) and KeyboardInterrupt, which keeps Ctrl+C from stopping the script. When you need a catch-all in a top-level loop (for instance, a daemon script logging failures instead of crashing), write except Exception as e:: system signals KeyboardInterrupt and SystemExit don’t inherit from Exception. See Are the sites up for a working example of catching network errors.

    Your own checks: raise

    Sometimes Python sees no error, yet the value breaks your logic: 70000 or -1 is a valid int, but not a valid TCP port. Raise the exception yourself with raise:

    def parse_port(text):
        port = int(text)
        if not 1 <= port <= 65535:
            raise ValueError(f"port out of range 1..65535: {port}")
        return port

    Now the caller catches both "abc" and "70000" with one except ValueError as e:, instead of scattering range checks across the script.

    Take it further

    A function read_or_default(path, default="") that reads a UTF-8 file and returns default if the file is missing

    Return Path(path).read_text(encoding='utf-8') inside try, and return default in except FileNotFoundError:.

    from pathlib import Path
    
    def read_or_default(path, default=""):
        try:
            return Path(path).read_text(encoding="utf-8")
        except FileNotFoundError:
            return default
    
    print(read_or_default("no_such.txt", "empty"))
    # empty
    Sum the integers in ["12", "bad", "8", "3.5", "5"], skipping invalid strings, and count how many were skipped

    Wrap int(item) in try/except ValueError; increment a skipped counter on failure.

    items = ["12", "bad", "8", "3.5", "5"]
    total = 0
    skipped = 0
    
    for item in items:
        try:
            total += int(item)
        except ValueError:
            skipped += 1
    
    print("Total:", total, "Skipped:", skipped)
    # Total: 25 Skipped: 2
    Run parse_port from above on ["22", "8080", "70000", "abc"] and print either the number or the error message for each item

    Call parse_port(raw) inside try in a loop, and print e inside except ValueError as e:.

    def parse_port(text):
        port = int(text)
        if not 1 <= port <= 65535:
            raise ValueError(f"port out of range 1..65535: {port}")
        return port
    
    for raw in ["22", "8080", "70000", "abc"]:
        try:
            print(raw, "->", parse_port(raw))
        except ValueError as e:
            print(raw, "-> error:", e)

    If it doesn’t work

    The script doesn’t crash, but the result is wrong — and the output is silent

    Cause
    A bare except: or except Exception: pass swallowed a typo in a variable name (NameError) or a wrong type (TypeError).
    Fix
    Catch only the specific error type (ValueError, FileNotFoundError), and let unexpected errors fail with a traceback.

    The script stopped responding to Ctrl+C

    Cause
    A bare except: catches even KeyboardInterrupt — the user’s interrupt signal.
    Fix
    Always name the exception class; when you need to catch general runtime errors, write except Exception as e: — KeyboardInterrupt isn’t under Exception.

    The traceback spans several files and it’s hard to tell where it broke

    Cause
    A traceback runs from the entry point down to the failure, so the top frames often belong to the launcher or the standard library.
    Fix
    Read from bottom to top: the last line names the type and reason; above it sits the line in your file that triggered it.

    The error landed in the wrong except branch

    Cause
    A broader class (such as OSError) comes before a narrower one (FileNotFoundError) in the except chain.
    Fix
    Put narrower exceptions before broader ones: FileNotFoundError first, OSError after.

    UnboundLocalError: cannot access local variable 'data' where it is not associated with a value

    Cause
    The variable was only assigned inside try, an error fired there, and code after except tried to read it.
    Fix
    Set a default value before try, or move the code that uses the result into an else branch.

    Also in this chapter