简体   繁体   English

如何访问 Python 的 catch 块中的 try 块中存在的变量值

[英]How to access variable value present from try block in the catch block in Python

I am trying to print the type of the value that is given as input in the try block when an exception is raised so that it gives a clear picture to the user as to what input is actually given and what needs to be given instead using the following code snippet in Python -我试图在引发异常时打印在 try 块中作为输入给出的值的类型,以便它向用户提供关于实际给出的输入以及需要给出什么而不是使用Python 中的以下代码片段 -

a = None
try:
    a = int(input('Enter a number'))
    print(a)

except ValueError:
    print('Control waited for Integer , but got a {}'.format(type(a)))

But unable to access the type of variable 'a' in the except block.但无法访问 except 块中的变量“a”的类型。 For example: when the user provides the input as True, I'd want the user to know that the control waited for integer but it received a boolean instead.例如:当用户提供输入为 True 时,我希望用户知道控件等待 integer 但它收到了 boolean 代替。 in python.在 python 中。 locals() function did not help. locals() function 没有帮助。 Any insights?有什么见解吗?

You need to split the input from the int parsing part, like this:您需要从int解析部分拆分input ,如下所示:

a = input('Enter a number ') # a gets assigned, no matter what
a = int(a) # if not an int, will throw the Exception, but a keeps the value assigned in the previous line

In your example, a will never get assigned within the try block if you don't enter an int .在您的示例中,如果您不输入int ,则不会在try块中分配a

Regarding where the input part should sit (I mean, outside or inside the try block), from a variable assignment perspective that is indifferent, given that in both cases a will be part of the global scope.关于input部分应该放在哪里(我的意思是,在try块之外或内部),从变量赋值的角度来看,这是无关紧要的,因为在这两种情况下, a都将是全局scope 的一部分。 Given that - for this specific case - input should be benign Exception-wise and won't throw a ValueError anyway, it may as well sit outside the try block.鉴于 - 对于这种特定情况 - input应该是良性的 Exception-wise 并且无论如何都不会抛出ValueError ,它也可能位于try块之外。

Just move the input out of the try except block and you are good.只需将输入移出 try except 块,就可以了。

a = input("Enter, a number")
try:
    a = int(a)
    print(a)

except ValueError:
    print('Control waited for Integer but {a} cannot be casted to int')

As others wrote, the in put is not assigned to a when the exception is raised.正如其他人所写,当引发异常时,输入未分配给a

When you are capturing exception, use a minimal try bloc;当您捕获异常时,请使用最小的try bloc;

a = input('Enter a number')
try:
    a = int(a)
except ValueError:
    print('Control waited for Integer , but got a {}'.format(type(a)))
print(a)

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

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