如何引发我的异常而不是内置异常? [英] How to raise my exceptions instead of built-in exceptions?

查看:51
本文介绍了如何引发我的异常而不是内置异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我需要引发异常,因为内置异常不适用于我的程序.定义异常后,python会同时引发我的异常和内置异常,如何处理这种情况?我只想打印我的吗?

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.')

输出:

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'

推荐答案

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

Add from None when raising your custom Exception:

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

有关更多信息,请参见 PEP 409-抑制异常上下文.

See PEP 409 -- Suppressing exception context for more information.

这篇关于如何引发我的异常而不是内置异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆