0

I want to add a sentence to every error message my Python program raise. Something like this:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    raise Exception
  Exception
AN ERROR OCCURRED, PLEASE ASK ABOUT IT ON STACKOVERFLOW!

I mean every exception, including the built-in ones. How can I do this?

4
  • 3
    Why? If it's associated with every excretion, isn't it kind of implicit? That seems like it will add noise more than anything. Is there an end goal that you're striving for? Commented Feb 29, 2020 at 1:22
  • This won't be pretty, Python's built-in exceptions are, well, built-in/extension types, i.e. they are implemented in C, and so you can't monkeypatch them. Commented Feb 29, 2020 at 1:24
  • 2
    You can wrap your whole code with try ending with a broad except Exception as e then print whatever you want and raise e. But seems a bit weird to be honest Commented Feb 29, 2020 at 1:25
  • 1
    This sounds like a case of the XY Problem to me. Can you provide some more context for this? Commented Feb 29, 2020 at 2:54

2 Answers 2

2

I am not sure if its possible to elegantly change all exception messages.

Here's the next best thing I could come up with. We are going to use decorators.

In general, decorators are like wrappers for functions. There is a good explanation for how they work here: https://youtu.be/7lmCu8wz8ro?t=2720

This is the one I came up with:

def except_message(message=''):
  def inner(f):
    def wrapper(*args, **kwargs):
      try:
        return f(*args, **kwargs)
      except Exception as e:
        raise type(e)(str(e) + "\n" + message).with_traceback(sys.exc_info()[2])
    return wrapper
  return inner

Atop a function that you want to use this decorator on, write @except_message(message='My_message') where 'My_message' is whatever you want the message to be. (It will add it to the end of the exception message)

Example:

@except_message(message='FOUND AN EXCEPTION')
def foo():
    raise Exception()

After it is run, the following is returned by the console:

Traceback (most recent call last):
  File "main.py", line 7, in wrapper
    return f(*args, **kwargs)
  File "main.py", line 15, in foo
    raise Exception()
Exception

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    foo()
  File "main.py", line 9, in wrapper
    raise type(e)(str(e) + "\n" + message).with_traceback(sys.exc_info()[2])
  File "main.py", line 7, in wrapper
    return f(*args, **kwargs)
  File "main.py", line 15, in foo
    raise Exception()
Exception:
FOUND AN EXCEPTION

If you only want the message you chose to appear, change in the decorator's function str(e) + "\n" + message to message.

Also, to change all exceptions to this message, you could wrap you code in a function (either by calling it inside a function in a different file or by simply changing the indentation) and then using the decorator.

Credits:

https://stackoverflow.com/a/6062799/5323429

https://stackoverflow.com/a/13898994/5323429

Sign up to request clarification or add additional context in comments.

Comments

1

You could override sys.excepthook as described in this answer which would then let you print what you want or modify the exception (as in Allan's answer) before passing it to the original sys.__excepthook__.

This should apply globally meaning you don't have to remember to wrap each function with a decorator.

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.