我正在尝试创建一个通用错误处理程序,类似于Oracle中的“其他人”。我可以找到的示例都涉及捕获特定的预期错误。
Try:
some_function()
Except: #I don't know what error I'm getting
show_me_error(type_of_error_and_message)
答案 0 :(得分:32)
try:
1/0
except Exception as e:
print '%s (%s)' % (e.message, type(e))
>>>
integer division or modulo by zero (<type 'exceptions.ZeroDivisionError'>)
这非常well-documented。
但您可能只需要Sentry吗?
答案 1 :(得分:2)
要使用Python 3打印异常,您将要使用type(e)
。下面的示例:
try:
1/0
except Exception as e:
print(type(e))
>>> <class 'ZeroDivisionError'>
然后您可以使用以下命令捕获异常:
try:
1/0
except ZeroDivisionError:
print('Cannot divide by 0')
except Exception as e:
print(type(e))
>>> Cannot divide by 0
答案 2 :(得分:1)
import traceback
try:
some_function()
except Exception as e:
trace_back = traceback.format_exc()
message = str(e)+ " " + str(trace_back)
print message
答案 3 :(得分:-1)
要在Python 3中打印异常,
try:
# your code
except Exception as e:
print(e)