catching NameError and Error Handling
I am writing a function which takes the user input:
def func(input):
I put in try an开发者_如何学运维d 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?
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.
精彩评论