简体   繁体   English

NameError: name 'variable' is not defined, 如何在try/except语句的finally块中处理和异常

[英]NameError: name 'variable' is not defined, how to handle and exception in the finally block of try/except statement

I am a bit new in python, and have just learned about the try except else and finally statement.我对 python 有点陌生,刚刚了解了 try except else 和 finally 语句。

try: 
   x=int(input("enter a number:")
except:
   print("you entered a wrong type of input, make sure to enter an integer value")
else:
   print(f"running in else : {x}")
finally: 
   print(f"finally : {x+2}")

This will cause another exception in finally block NameError name 'x' is not defined if I enter anything other than an integer value in my input statement如果我在输入语句中输入除 integer 值以外的任何值,这将导致 finally 块中的另一个异常NameError name 'x' is not defined

Does it mean we have to put all that is related to x in the else block and all that have nothing to do with x, in the finally block?这是否意味着我们必须将所有与 x 相关的内容放在 else 块中,而将所有与 x 无关的内容放在 finally 块中?

My actual script is very long but I'm trying to understand this concept from a smaller example我的实际脚本很长,但我试图从一个较小的例子中理解这个概念

Is this a right intuition?这是正确的直觉吗?

Please suggest me if otherwise否则请建议我

I am inclined to think that you would want to give the user a second chance, and a third, and...我倾向于认为你会想给用户第二次机会,第三次,然后......

So why not wrap it in a while-loop to enforce the presence of an x which is an integer at the end:那么为什么不将它包装在一个while循环中以强制存在一个x,它最后是一个integer:

x=None
while x is None:
    try: 
       x=int(input("enter a number:"))
    except ValueError:
       print(f"You entered a wrong type of input, make sure to enter an integer value")

Finally blocks executes No matter what (unless you destory the laptop/PC).无论如何,最终块都会执行(除非您破坏了笔记本电脑/PC)。

No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled.无论之前发生了什么,一旦代码块完成并处理任何引发的异常,就会执行最终块。 Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.即使异常处理程序或 else 块中存在错误并且引发了新异常,最终块中的代码仍会运行。

But, In this case you can use flags inside the final statement.但是,在这种情况下,您可以在final语句中使用flags

final = True  #Flag true 

try: 
   x=int(input("enter a number:"))
except:
   print("you entered a wrong type of input, make sure to enter an integer value")
   final = False  #Flase if except
      
else:
   print(f"running in else : {x}")
finally:
   if final:
       
       print(f"finally : {x+2}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM