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

标签 python custom-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获取更多信息。

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

相关文章:

Java 异常处理自定义类

python - sqlalchemy filter_by() 又多了一个参数

python - 使用 python3.x 在 Linux 中查看分区

python - PyInstaller 和超过 8 个字符的 MEIPASS 文件夹

java - 无效异常

C# 网络服务 : Throw exception with extra properties in JSON

python - python-ldap 的异常是否按层次结构组织?

python - 将稀疏矩阵 (csc_matrix) 转换为 pandas 数据帧

python - PostgreSQL: "database does not exist"

c++ - 捕获多个自定义异常? - C++