这个函数正确吗?

2024-04-20 08:57:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在某些异常情况下调用该函数是否正确? 这个过程正确吗?处理每个异常是否更好?你知道吗

def close_all():
        try:
                ftp.close()
        except:
                pass
        try:
                tar.close()
        except:
                pass
        try:
                savelist.close()
        except:
                pass
        try:
                os.remove(tarname)
        except:
                pass
        exit()

提前谢谢。你知道吗


Tags: 函数closeos过程defftppasstar
1条回答
网友
1楼 · 发布于 2024-04-20 08:57:06

我认为你应该一个一个地处理每一个异常。这将缩短您的代码。首先注意ftp.close()和其他方法将引发的所有异常。然后逐一处理。你知道吗

示例:

>>> a = 5        # a is an integer
>>> b = "Bingo"  # b is a string
>>>
>>> def add_five():
        try:
            c + 5  # c is not defined. NameError exception is raised
        except NameError:
            b + 5  # b is a string. TypeError exception is raised
        except TypeError:
            a + 5  # a is int. No exception is raised
        except:
            # This last except clause is just in case you forgot to handle any exception
            pass 
>>>

相关问题 更多 >