关于捕获任何异常

如何编写捕获全部异常的try / except块? html


#1楼

您能够执行此操做来处理常规异常 python

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

#2楼

要捕获全部可能的异常,请捕获BaseException 。 它位于异常层次结构之上: 测试

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

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))

但正如其余人提到的那样,除非你有充分的理由,不然你一般不会这样作。 spa


#3楼

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

try:
    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception

#4楼

try:
    whatever()
except:
    # this will catch any exception or error

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


#5楼

你能够,但你可能不该该: htm

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

可是,这也会捕获像KeyboardInterrupt这样的异常,你一般不但愿这样,是吗? 除非您当即从新提出异常 - 请参阅文档中的如下示例: ip

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