在某些情况下,我需要引发异常,因为内置异常不适用于我的程序。定义异常后,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'
答案 0 :(得分:3)
在引发自定义异常时添加from None
:
raise MyExceptions('age should be an integer, not str.') from None
有关更多信息,请参见PEP 409 -- Suppressing exception context。
答案 1 :(得分:3)
尝试将from lxml import html
raw_source = """<html>
<a href="HarryPotter:Chamber of Secrets">
text
</a>
<a href="HarryPotter:Prisoners in Azkabahn">
text
</a>
</html>"""
source = html.fromstring(raw_source)
for link in source.xpath('//a'):
print(link.xpath('substring-after(@href, "HarryPotter:")'))
更改为raise MyExceptions('age should be an integer, not str.')
答案 2 :(得分:0)
您可以禁止异常上下文,并将消息从ValueError
传递到您的自定义异常:
try:
int(age)
except ValueError as e:
raise MyException(str(e)) from None
# raise MyException(e) from None # works as well