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

Python 如何引发我的异常而不是内置异常?,python,custom-exceptions,Python,Custom Exceptions,在某些情况下,我需要引发异常,因为内置异常不适合我的程序。在我定义了我的异常之后,python同时引发了我的异常和内置异常,如何处理这种情况?我只想打印我的 class MyExceptions(ValueError): """Custom exception.""" pass try: int(age) except ValueError: raise MyExceptions('age should be an integer, not str.') 输出

在某些情况下,我需要引发异常,因为内置异常不适合我的程序。在我定义了我的异常之后,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.
回溯(最近一次呼叫最后一次):
文件“new.py”,第10行,在
智力(年龄)
ValueError:基数为10的int()的文本无效:“圣诞快乐”
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“new.py”,第12行,在
raise MyExceptions('年龄应该是整数,而不是str.)
__main.MyExceptions:age应该是整数,而不是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'
回溯(最近一次呼叫最后一次):
文件“new.py”,第10行,在
智力(年龄)
MyException:以10为基数的int()的文本无效:“圣诞快乐”

在引发自定义异常时,从无添加

raise MyExceptions('age should be an integer, not str.') from None
try:
    int(age)
except ValueError as e:
    raise MyException(str(e)) from None
    # raise MyException(e) from None  # works as well

有关更多信息,请参见。

尝试将
raise MyExceptions('age应为整数,而非str')更改为
raise MyExceptions('age应为整数,而非str'),从None开始

您可以抑制异常上下文,并将消息从
VALUERROR
传递给自定义异常:

raise MyExceptions('age should be an integer, not str.') from None
try:
    int(age)
except ValueError as e:
    raise MyException(str(e)) from None
    # raise MyException(e) from None  # works as well

可能重复@tk421这似乎不是该问题的重复。