首页 文章

尝试和另外两个函数调用时执行

提问于
浏览
1

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

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时,都会尝试#2和#2除外!原因创建了directory1并打印了错误消息1,同样我的info变量等于None .

如何在第二个函数混乱中调用function1尝试除了子句?

谢谢 !

2 回答

  • 0

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

  • 3

    为什么令人惊讶? try 块应该执行,直到某些 exception 被引发,之后 except 块将被执行 . 那么为什么看起来这两个块都被执行 in spite of an exception

    其中一个最可能的原因是 try 块中存在与引发的异常无关的内容 . 这是 else 块的主要原因 . 按如下方式重构代码可能会有所帮助

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

    如果它是一大块代码,那么 else 块会更加丰富,事情可能会顺利进行 .

相关问题