【问题标题】:Try and except both executed when called by another function当被另一个函数调用时,try and except 都执行
【发布时间】:2016-08-08 07:31:35
【问题描述】:

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

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中调用function1时,try#2和except#2都被执行了!原因 directory1 已创建并打印错误消息 1,我的 info 变量也等于 None。

如何在第二个函数混乱中调用 function1 和 except 子句?

谢谢!

【问题讨论】:

  • 可能在那之后出现了错误。也许将页面内容写入文件。
  • @zondo 无论如何,被main调用时有效,被其他函数调用时无效

标签: python python-3.x exception error-handling


【解决方案1】:

如果在执行 try #2 的主体时引发异常,显然除了 #2 将被执行。您可能应该检查引发了哪种异常以及在哪一行。

【讨论】:

    【解决方案2】:

    为什么会令人惊讶? try 块应该执行到一些 exception 被提升,然后 except 块将执行。那么为什么看起来两个块都执行了尽管有异常

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2016-10-31
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多