user1050619
user1050619

Reputation: 20906

Custom exception error message using python

I'm trying to generate a custom exception message but get the below error -

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)

Error:-

    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

Upvotes: 0

Views: 68

Answers (3)

azundo
azundo

Reputation: 6052

If you want to retain the original traceback you can instead do:

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

Upvotes: 0

Ewen Gillies
Ewen Gillies

Reputation: 76

You've close, but you're calling the instance instead of the type. We can build a new instance by grabbing the type of the exception using type 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)
    error_constructor = type(ex)
    raise error_constructor(e)

Upvotes: 0

chepner
chepner

Reputation: 532238

ex is an instance of ZeroDivisionError, not the type ZeroDivisionError itself.

raise type(ex)(e)

Upvotes: 2

Related Questions