[英]Try and except both executed when called by another function
There's something weird happening with my code, I have a first function that goes like this : 我的代码发生了一些奇怪的事情,我的第一个函数是这样的:
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
So this function works perfectly when called in the main program, but when I try to call function1 in another function2, both try#2 and except#2 are executed ! 因此,当在主程序中调用此函数时,该函数可以完美运行,但是当我尝试在另一个function2中调用function1时,将同时执行try#2和exception#2! Cause directory1 is created and error message 1 is printed, also my info variable equals None.
原因创建了directory1并打印了错误消息1,我的info变量也等于None。
How can calling function1 in a second function mess try and except clauses ? 如何在第二个函数中调用function1使try和except子句混乱?
Thank you ! 谢谢 !
Why is it surprising? 为什么令人惊讶?
try
block is supposed to execute till some exception
is raised and after that except
block will execute. try
执行try
块,直到引发某些exception
为止,然后执行except
块。 So why does it look like both blocks got executed in spite of an exception ? 那么,为什么看起来两个块都尽管发生了异常却被执行了 ?
One of the most likely reasons is there are stuff in try
block that has nothing to do with the exception being raised. 最可能的原因之一是
try
块中存在与引发异常无关的内容。 That's the primary reason for the else
block. 这是
else
块的主要原因。 Refactoring your code as follows might help 如下重构代码可能会有所帮助
try:
# only statements that might raise exception
except SomeException:
# except block
else:
# everything you wanted do if no exception was raised
If it's a big chunk of code, fatter the else
block, things are likely to go smoothly. 如果这是一大堆代码,则增加
else
块,事情可能会顺利进行。
If an exception is raised while executing body of try #2 , obviously except #2 will be executed. 如果在执行try#2的主体时引发异常,则显然将执行#2除外。 You probably should check what kind of exception is raised and at which line.
您可能应该检查引发哪种异常以及在哪一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.