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

使用python的自定义异常错误消息,python,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) 错误:-

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

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
1/0
ZeroDivision错误:被零除
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py”,第197行,在runfile中
pydev_imports.execfile(文件名、全局变量、本地变量)#执行脚本
文件“/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py”,execfile中第18行
exec(编译(内容+“\n”,文件,'exec'),全局,loc)
文件“/Users/lakshmananp2/PycharmProjects/Scratch/exception.py”,第9行,在
提高行政长官(e)
TypeError:“ZeroDivisionError”对象不可调用
ex
ZeroDivisionError
的一个实例,而不是类型
ZeroDivisionError
本身

raise type(ex)(e)
ex
ZeroDivisionError
的一个实例,而不是类型
ZeroDivisionError
本身

raise type(ex)(e)

您已经关闭,但您正在调用实例而不是类型。我们可以通过使用builtin获取异常类型来构建一个新实例:


您已经关闭,但您正在调用实例而不是类型。我们可以通过使用builtin获取异常类型来构建一个新实例:


如果要保留原始回溯,可以执行以下操作:

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

如果要保留原始回溯,可以执行以下操作:

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