Python尝试一些额外的逻辑

时间:2016-04-12 16:27:24

标签: python

您好我正在努力尝试'尝试'只能在一种条件下工作:

try:
    print "Downloading URL: ", url
    contents = urllib2.urlopen(url).read()
except:
    message = "No record retrieved."
    print message
    return None

如果kwarg nodownload为True,我不希望上面的代码有效。

所以我尝试了以下内容:

try:
    if nodownload:
        print "Not downloading file!"
        time.sleep(6)
        raise
    print "Downloading URL: ", url
    contents = urllib2.urlopen(url).read()
except:
    message = "No record retrieved."
    print message
    return None

无论是否在命令行中传递--nd参数,上述内容始终都会下载。下面总是跳过文件而不是传递参数。

    if not nodownload:
        print "Not downloading file!"
        time.sleep(6)
        raise
    print "Downloading URL: ", url
    contents = urllib2.urlopen(url).read()
except:
    message = "No record retrieved."
    print message
    return None

在命令行中没有输入下载:

parser.add_argument('--nodownload', dest='nodownload', action='store_true',
                    help='This doesn't work for some reason')

2 个答案:

答案 0 :(得分:1)

您可以在需要时使用raise导致异常,从而使try失败。

答案 1 :(得分:0)

正如其他人所说,人们可以提出异常。

除了使用预定义的例外,您还可以使用自己的例外:

class BadFriend(Exception):
    pass


class VirtualFriend(Exception):
    pass


class DeadFriend(Exception):
    pass


try:
    name = raw_input("Tell me name of your friend: ")
    if name in ["Elvis"]:
        raise DeadFriend()
    if name in ["Drunkie", "Monkey"]:
        raise BadFriend()
    if name in ["ET"]:
        raise VirtualFriend()
    print("It is nice, you have such a good friend.")
except BadFriend:
    print("Better avoid bad friends.")
except VirtualFriend:
    print("Whend did you shake hands with him last time?")
except DeadFriend:
    print("I am very sorry to tell you, that...")

你甚至可以通过引发异常传递一些数据,但要注意不要滥用太多(如果 标准结构正在运行,使用更简单的结构。)