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

主宰稳场 提交于 2021-01-27 19:07:46

问题


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'

回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/54020122/how-to-raise-my-exceptions-instead-of-built-in-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!