这个功能是否正确?

时间:2014-11-24 15:11:12

标签: 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()

提前致谢。

1 个答案:

答案 0 :(得分:1)

我认为你应该逐个处理每个例外。这会缩短你的代码。首先要注意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 
>>>