小编big*_*ian的帖子

在python中定义异常的频率应该多少?

为了消除python模块中潜在的竞争条件,我写了一些专门的工作流程,我学会了python的"更容易请求宽恕而不是许可"(EAFP)编码风格,我现在用try /提高了许多自定义异常除了我曾经使用的块,如果/ thens.

我是python的新手,这种EAFP风格在逻辑上是有道理的,似乎让我的代码更加健壮,但有些事情让人觉得有些过分.为每种方法定义一个或多个异常是不好的做法吗?

这些自定义异常往往只对单个方法有用,虽然它感觉像是一个功能正确的解决方案,但似乎需要维护很多代码.

这里有一个示例方法,例如:

class UploadTimeoutFileMissing(Exception):
    def __init__(self, value):
        self.parameter = value
    def __str__(self):
        return repr(self.parameter)

class UploadTimeoutTooSlow(Exception):
    def __init__(self, value):
        self.parameter = value
    def __str__(self):
        return repr(self.parameter)

def check_upload(file, timeout_seconds, max_age_seconds, min_age_seconds):

    timeout = time.time() + timeout_seconds

    ## Check until file found or timeout
    while (time.time() < timeout):

        time.sleep(5)
        try:
            filetime = os.path.getmtime(file)
            filesize = os.path.getsize(file)
        except OSError:
            print "File not found %s" % file
            continue

        fileage = time.time() - filetime

        ## Make sure file isn't pre-existing …
Run Code Online (Sandbox Code Playgroud)

python

16
推荐指数
1
解决办法
2267
查看次数

标签 统计

python ×1