使用python的自定义异常错误消息

时间:2019-08-23 20:46:04

标签: python

我正在尝试生成自定义异常消息,但出现以下错误-

import time
try:
    start_time = time.time()
    1/0
except Exception as ex:
    elapsed_time = (time.time() - start_time)/60
    e = "elapsed time(in mins) - {0}".format(elapsed_time)
    print(type(ex))
    raise ex(e)

错误:-

    1/0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/lakshmananp2/PycharmProjects/Scratch/exception.py", line 9, in <module>
    raise ex(e)
TypeError: 'ZeroDivisionError' object is not callable

3 个答案:

答案 0 :(得分:2)

exZeroDivisionError实例,而不是类型ZeroDivisionError本身。

raise type(ex)(e)

答案 1 :(得分:0)

您已经关闭,但是您正在调用实例而不是类型。我们可以使用type内置的异常类型来构建新实例:

import time
try:
    start_time = time.time()
    1/0
except Exception as ex:
    elapsed_time = (time.time() - start_time)/60
    e = "elapsed time(in mins) - {0}".format(elapsed_time)
    error_constructor = type(ex)
    raise error_constructor(e)

答案 2 :(得分:0)

如果要保留原始的追溯,可以改为:

import time
try:
    start_time = time.time()
    1/0
except Exception as ex:
    elapsed_time = (time.time() - start_time)/60
    e = "elapsed time(in mins) - {0}".format(elapsed_time)
    ex.__init__(e)
    raise  # re-raises ex with the original line number