gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:56:56 24 4
gpt4 key购买 nike

在某些情况下,我需要引发异常,因为内置异常不适合我的程序。在我定义了我的异常之后,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获取更多信息。

关于python - 如何引发我的异常而不是内置异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54020122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com