在`try`语句中如何报告未指定错误的类型/名称? python 2
这里有一个我想说的简单例子 -
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)
第二个异常的正确写法是什么?
提前谢谢你们 :)
3 个回答
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
0
正如Jason所提到的,如果你想捕捉所有的异常,包括KeyboardInterrupt
(就是你按下Ctrl+C时的那个),你可以使用except Exception as O
或者except BaseException as O
。
如果你需要获取异常的名字,可以用name = O.__class__.__name__
或者name = type(O).__name__
。
希望这对你有帮助。
4
except Exception as exc:
Exception
是所有“内置的、非系统退出的异常”的基础类,用户自定义的异常也应该以它为基础。因此,except Exception
可以捕捉到所有的异常,除了那些不属于 Exception
的少数几种,比如 SystemExit
(系统退出)、GeneratorExit
(生成器退出)和 KeyboardInterrupt
(键盘中断)。