[英]Python: Only running exception block when try block fails
I am having trouble understanding how to write a try except block that only runs one block or the other not just half the block and then move to the exception as seen in my example f or emphasis I do not wish to run any portion of try if any line in try fails 我很难理解如何编写try除外块,该块仅运行一个块或另一个块而不是仅运行一半块,然后移至异常,如我的示例f 或强调中所示,我不想运行try的任何部分,如果尝试中的任何行都会失败
x = 1
y = 1
try:
x = x+1
print(x)
x.append(1)
except:
print(x)
which returns 哪个返回
2
2
instead of returning 而不是返回
1
as I would of expected. 如我所料。 This is problematic for me because I was foolishly under the impression that only except block would be executed upon try failure.
这对我来说是有问题的,因为我愚蠢地认为,只有try失败时才会执行else块。 I am scraping websites using beautiful soup and my allocation of a soup usually will throw the exception and the other block will run but unforeseen errors after this allows some lists to be appended then runs the exception block and appends them again.
我正在使用漂亮的汤抓取网站,我分配的汤通常会引发异常,其他块将运行,但在允许添加一些列表然后运行异常块并再次追加之后,出现无法预料的错误。 leaving me with lists of different lengths depending on where they fall within each block.
根据它们在每个块中的位置,给我留下不同长度的列表。
any help is much appreciated 任何帮助深表感谢
You could reset the computed_result to value of x
in except-block on error: 您可以在出现错误时在except-block中将compute_result重置为
x
值:
x = 1
y = 1
computed_value = 0
try:
computed_value = x + 1
#print(fallback_var)
computed_value.append(1)
print("Exceution succeed: keeping value")
except:
print("Exceution failed: resetting value")
computed_value = x
#print(x)
print(computed_value)
Let's go step by step: 让我们一步一步走:
Your code correctly executes x=x+1
(now x is 2). 您的代码正确执行
x=x+1
(现在x为2)。
Then it correctly executes print(x)
(so it prints 2). 然后,它将正确执行
print(x)
(因此将打印2)。
Then it tries to execute x.append(1)
(and fails) 然后它尝试执行
x.append(1)
(并失败)
Since it has failed to append(1)
it enters the except and executes print(x)
(so it prints 2) 由于未成功
append(1)
因此输入except,然后执行print(x)
(因此将打印2)
It outputs exactly what's expected. 它输出的正是预期的结果。
This run both. 这两者都运行。
Your code 您的密码
try:
x = x+1
print(x)
x.append(1)
except:
print(x)
When python start execution, it execute line by line 当python开始执行时,它逐行执行
x = x + 1
After this x
become 2
. 之后,
x
变为2
。
then 然后
print (x)
Print 2
as first in your output. 在输出中首先打印
2
。
x.append(1)
Above statment raise exception which is caught by except
clause in your code. 以上语句引发异常,该异常在您的代码中被
except
子句捕获。
Please remember, x
value is already change to 2
in x = x + 1
statment. 请记住,在
x = x + 1
陈述中, x
值已更改为2
。 In except
when you do 在
except
当你做
print (x)
It print 2
again. 再次打印
2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.