【问题标题】:Why doesn't exception work? [closed]为什么异常不起作用? [关闭]
【发布时间】:2013-12-28 06:22:21
【问题描述】:

我有一个 python 代码,我想引发异常:

def main():
    try:
        if testfile == 'testfile':
            write_file(create_output())
            print_file()
            return 0
    except:
        return 1

即使 testfile != 'testfile' 函数不返回 1。为什么?

【问题讨论】:

  • 也许不会引发异常。如果您想引发异常,请使用 ... raise 关键字:) 您的最后一条评论表明您想要而不是 if...else 构造不是 try...except
  • 你首先想通过这段代码实现什么? (即,为什么这个问题被标记为unit-testing?)

标签: python unit-testing exception-handling


【解决方案1】:

从你的最后一句话来看,我认为你实际上想在这里使用if/else

def main():
    if testfile == 'testfile':
        write_file(create_output())
        print_file()
        return 0
    else:
        return 1

try/except 用于捕获/处理错误,而不是根据条件做一件事或另一件事。这就是if/else 的用途。

【讨论】:

    【解决方案2】:

    您没有提出任何异常。您只是在处理可能引发的任何异常。如果您决定通过异常处理此问题,请尝试使用assert。如果testfile 不等于'testfile',这将引发AssertionError

    def main():
        try:
            assert testfile == 'testfile'
            write_file(create_output())
            print_file()
            return 0
        except:
            return 1
    

    否则 iCodez 指出,在这种情况下使用if/else 更合适。

    【讨论】:

      【解决方案3】:

      您可能不了解异常是什么以及何时引发。 两个字符串之间的比较将返回一个布尔值,它不会引发异常。 异常是针对错误的。如果 testfile != 'testfile' 您的代码不会出错,而只是一个 False 的条件语句。 我建议你阅读一些documentation

      【讨论】:

        【解决方案4】:

        为了引发异常,必须先抛出异常。在上面的代码块中,除非 write_file 或 print_file 引发异常,否则不会发生。您需要执行 if/else 以返回 1。如果这是 testfile == 'testfile,请执行某些操作,否则返回 1。

        【讨论】:

          猜你喜欢
          • 2018-02-15
          • 2018-02-15
          • 2017-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多