如何引发我的异常而不是内置异常?

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

在某些情况下,我需要提出异常,因为内置异常不适合我的程序。在我定义了我的异常后,python 引发了我的异常和内置异常,如何处理这种情况?我只想打印我的?

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

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

输出:

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.

我想打印这样的东西:

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

在引发自定义异常时添加 from None

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

有关详细信息,请参阅 PEP 409 -- Suppressing exception context

尝试将 raise MyExceptions('age should be an integer, not str.') 更改为 raise MyExceptions('age should be an integer, not str.') from None

您可以抑制异常上下文并将消息从 ValueError 传递到您的自定义异常:

try:
    int(age)
except ValueError as e:
    raise MyException(str(e)) from None
    # raise MyException(e) from None  # works as well