3

这是我的意思的一个简单示例-

try:
    something_bad

# This works -
except IndexError as I:
    write_to_debug_file('there was an %s' % I)

# How do I do this? -
except as O:
    write_to_debug_file('there was an %s' % O)

第二个异常的正确语法是什么?

提前致谢 :)

4

3 回答 3

4

except Exception as exc:

Exception是所有“内置、非系统退出异常”的基类,也应该是用户定义异常的基类。except Exception因此将捕获除少数不子类之外的所有内容Exception,例如SystemExit, GeneratorExit, KeyboardInterrupt.

于 2014-08-11T05:26:49.483 回答
0

您不必指定错误类型。只需用于sys.exc_info()读出最后一个异常:

import sys

try:
    foobar

except:
    print "Unexpected error of type", sys.exc_info()[0].__name__
    print "Error message:", sys.exc_info()[1]

参考:https ://docs.python.org/2/tutorial/errors.html#handling-exceptions

于 2014-08-11T04:49:32.800 回答
0

正如 Jason 已经指出的那样,您可以使用except Exception as Oorexcept BaseException as O如果您想捕获所有异常,包括KeyboardInterrupt.

如果您需要异常的名称,您可以使用name = O.__class__.__name__name = type(O).__name__

希望这可以帮助

于 2014-08-11T06:08:44.383 回答