'Python NameError exception not working as intended

When I run this code, a NameError traceback error pops up, even though it should be handled by the exception. Why is that? The function call argument is intentionally misspelled.

filename_cats = "cats.txt"
filename_dogs = "dogs.txt"

def readlines(filename):
    """read lines from a text file"""
    try:
        with open(filename) as f:
            lines = f.readlines()
        string = ''
        for line in lines:
            string += line
    except (NameError, FileNotFoundError):
        print(f"The file {filename} was not found.")
    else:
        print(string)

readlines(filename_cat)


Solution 1:[1]

It's because the error happens here:

              ?
readlines(filename_cat) ?
              ??

Not anywhere in here:

try:
    with open(filename) as f:
        lines = f.readlines()
    string = ''
    for line in lines:
        string += line
except (NameError, FileNotFoundError):

A try..except block can only catch errors happening literally within it, not anything happening before or after it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 deceze