首页 文章

关于捕获任何异常

提问于
浏览
490

如何编写能够捕获所有异常的 try / except 块?

7 回答

  • 42

    你可以,但你可能不应该:

    try:
        do_something()
    except:
        print "Caught it!"
    

    但是,这也会捕获像 KeyboardInterrupt 这样的异常,你通常不希望这样,是吗?除非您立即重新引发异常 - 请参阅以下示例from the docs

    try:
        f = open('myfile.txt')
        s = f.readline()
        i = int(s.strip())
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)
    except ValueError:
        print "Could not convert data to an integer."
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
    
  • 37

    除了一个完整的 except: 条款(正如其他人所说的那样你不应该使用),你可以简单地 grab Exception

    import traceback
    import logging
    
    try:
        whatever()
    except Exception as e:
        logging.error(traceback.format_exc())
        # Logs the error appropriately.
    

    您通常只会考虑在代码的最外层执行此操作,例如,您希望在终止之前处理任何其他未捕获的异常 .

    except Exception 优于 except 的优点是,它有一些例外,它们不会捕获,最明显是 KeyboardInterruptSystemExit :如果你 grab 并吞下那些,那么你可能会让任何人都难以退出你的脚本 .

  • 422

    您可以这样做来处理一般异常

    try:
        a = 2/0
    except Exception as e:
        print e.__doc__
        print e.message
    
  • 4

    很简单的例子,类似于这里找到的例子:

    http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

    如果您尝试捕获所有异常,则将所有代码放在“try:”语句中,代替'print'执行可能引发异常的操作 . “' .

    try:
        print "Performing an action which may throw an exception."
    except Exception, error:
        print "An exception was thrown!"
        print str(error)
    else:
        print "Everything looks great!"
    finally:
        print "Finally is called directly after executing the try statement whether an exception is thrown or not."
    

    在上面的示例中,您将按以下顺序查看输出:

    1)执行可能引发异常的动作 .

    2)最后在执行try语句后直接调用是否抛出异常 .

    3)“抛出异常!”或者“一切看起来都很棒!”取决于是否抛出异常 .

    希望这可以帮助!

  • 11

    要捕获所有可能的异常,请 grab BaseException . 它位于异常层次结构之上:

    Python 3:https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy

    Python 2.7:https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy

    try:
        something()
    except BaseException as error:
        print('An exception occurred: {}'.format(error))
    

    但正如其他人提到的那样,除非你有充分的理由,否则你通常不会这样做 .

  • 86

    我刚刚发现了这个小技巧,用于测试Python 2.7中的异常名称 . 有时我在代码中处理了特定的异常,所以我需要一个测试来查看该名称是否在处理的异常列表中 .

    try:
        raise IndexError #as test error
    except Exception as e:
        excepName = type(e).__name__ # returns the name of the exception
    
  • 600
    try:
        whatever()
    except:
        # this will catch any exception or error
    

    值得一提的是,这不是正确的Python编码 . 这将捕获您可能不想捕获的许多错误 .

相关问题