catching NameError and Error Handling

11,538

NameError is usually caused by undefined variable name. If you use testInput as a variable name, i.e., without the quotes, you have to define it first. Try something like this:

testInput = "my_input_test"
func(testInput)

Or you can just use the string itself as the argument:

func("my_input_test")

Sometimes typos can also result in undefined variable name, and then a NameError.

Sounds like your try ... except statements are inside your function, the error is happened before the function body is executed, so you can't capture it inside the function body. To demonstrate how this error can be caught, you can try the following code.

# !!! DEMO ONLY. DON'T DO THIS.
try:
    func(testInput)
except NameError:
    # Your code here

IMPORTANT: NameErrors are normally an indication that you need to fix your variable/function/class names. Using try ... except to catch them is generally a bad practice and will lead to messy and unusable code.

Share:
11,538
Mike Lee
Author by

Mike Lee

Updated on June 04, 2022

Comments

  • Mike Lee
    Mike Lee almost 2 years

    I am writing a function which takes the user input:

    def func(input):
    

    I put in try and excepts to make sure the input is of the type I want. However, when I put in testInput, it throws a NameError vs "testInput".

    I understand why as it is thinking testInput is a variable name while it knows "testInput" is a string.

    Is there an intelligent way to catch this error?

    • Chris Phillips
      Chris Phillips about 13 years
      I don't think there's enough information here to answer your question adequately. Could you provide an actual example of the function and the calling code?
  • jfs
    jfs about 13 years
    it is not a good idea to catch NameError you should fix the code instead.
  • Wang Dingwei
    Wang Dingwei about 13 years
    @J.F. Totally agree with you. I've mentioned that in my last sentence.
  • jfs
    jfs about 13 years
    This confirms a general rule that invalid code fragments should not be present in a textbook or at least that there should be a more prominent warning: "DON'T DO IT".