0

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

3 Answers 3

2

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

raise type(ex)(e)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.