2

In some cases, I need to raise my exception because built-in exceptions are not fit to my programs. After I defined my exception, python raises both my exception and built-in exception, how to handle this situation? I want to only print mine?

class MyExceptions(ValueError):
    """Custom exception."""
    pass

try:
    int(age)
except ValueError:
    raise MyExceptions('age should be an integer, not str.')

The output:

Traceback (most recent call last):
  File "new.py", line 10, in <module>
    int(age)
ValueError: invalid literal for int() with base 10: 'merry_christmas'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "new.py", line 12, in <module>
    raise MyExceptions('age should be an integer, not str.')
__main__.MyExceptions: age should be an integer, not str.

I want to print something like this:

Traceback (most recent call last):
  File "new.py", line 10, in <module>
    int(age)
MyException: invalid literal for int() with base 10: 'merry_christmas'
Bahram Aghaei
  • 40
  • 1
  • 6
  • 3
    Possible duplicate of [Proper way to declare custom exceptions in modern Python?](https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python) – tk421 Jan 03 '19 at 10:15
  • 1
    @tk421 This does not appear to be a duplicate of that question. – khelwood Jan 03 '19 at 10:20

3 Answers3

3

Add from None when raising your custom Exception:

raise MyExceptions('age should be an integer, not str.') from None

See PEP 409 -- Suppressing exception context for more information.

finefoot
  • 9,914
  • 7
  • 59
  • 102
3

Try changing raise MyExceptions('age should be an integer, not str.') to raise MyExceptions('age should be an integer, not str.') from None

Sam
  • 75
  • 3
0

You can supress the exception context and pass the message from the ValueError to your custom Exception:

try:
    int(age)
except ValueError as e:
    raise MyException(str(e)) from None
    # raise MyException(e) from None  # works as well
user2390182
  • 72,016
  • 6
  • 67
  • 89