gpt4 book ai didi

python - Try 和 except 都在被另一个函数调用时执行

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:45 27 4
gpt4 key购买 nike

我的代码发生了一些奇怪的事情,我的第一个函数是这样的:

def function1():
try : #1
#try to open a file
#read file
#return info variable from the file
except : #1
try : #2
#try to open a web page
#read web page
if directory1 not in directorylist :
#create directory1
#change working directory to directory1
else :
#change working directory to directory1
#write web page content in a file
#return info variable from the file
except : #2
try : #3
#try to open a second web page
#print error message 1
except : #3
#print error message 2
#set info variable to None
#return info variable

所以这个函数在主程序中调用时完美运行,但是当我尝试在另一个函数 2 中调用函数 1 时,try#2 和 except#2 都被执行了!因为创建了 directory1 并打印了错误消息 1,我的信息变量也等于 None。

在第二个函数中调用 function1 怎么会弄乱 try 和 except 子句?

谢谢!

最佳答案

为什么令人惊讶? try block 应该一直执行到某个 exception 出现,之后 except block 将执行。那么为什么看起来两个 block 都执行了尽管有异常

最可能的原因之一是 try block 中的内容与引发的异常无关。这是 else block 的主要原因。按如下方式重构您的代码可能会有所帮助

try:
# only statements that might raise exception
except SomeException:
# except block
else:
# everything you wanted do if no exception was raised

如果是一大段代码,加厚 else block ,事情可能会顺利进行。

关于python - Try 和 except 都在被另一个函数调用时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36662174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com