0

I have the following custom exception class I created:

class MyException(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

    def __str__(self):
        return f"MyException error -> {self.message}"

My goal is to only show the exception message, not the full traceback. For example:

try:
    int('a')
except ValueError:
    raise MyException("Incorrect value")

should output only MyException: MyException error -> Incorrect value

This result can be achieved with sys.tracebacklimit = 0, however, I want to apply this only to my custom exception class. Moreover, I don't want to use print statements to output exception message.

Any help will be appreciated.

cornisto
  • 119
  • 2
  • 9
  • This seems like an [XY problem](https://xyproblem.info/) to me. IMO the thing that is raising an exception shouldn't have any say in how that exception is presented to the user. Instead it seems like the calling code should `except MyException` and handle it specially if necessary. – 0x5453 Aug 18 '22 at 16:10
  • 1
    would this work for you? https://stackoverflow.com/a/41414413/13592469 – n4321d Aug 18 '22 at 16:20
  • @n4321d not exactly what I wanted at first, but it will do the job too. Thanks a lot! – cornisto Aug 21 '22 at 16:59

0 Answers0