How to raise my exceptions instead of built-in exceptions?

326 Views Asked by At

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'
3

There are 3 best solutions below

0
finefoot On BEST ANSWER

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.

0
Sam On

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

0
user2390182 On

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