且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python函数可能引发哪些异常?

更新时间:2021-09-09 03:18:01

告诉我们某些异常可能引发的异常的唯一方法是查看文档。 int()文档未说明可能会引发ValueError的事实是文档中的错误,但ValueValue正是出于此目的,并且被每个人都知道而容易解释。

The only way to tell what exceptions something can raise is by looking at the documentation. The fact that the int() documentation doesn't say it may raise ValueError is a bug in the documentation, but easily explained by ValueError being exactly for that purpose, and that being something "everybody knows".

不过,要弄清楚这一点,文档是告诉您应该关注哪些异常的唯一方法。实际上,任何函数都可能引发任何异常,即使仅仅是因为信号可能到达而信号处理程序也可能引发异常。但是,您不应预期或处理这些错误;您应该只处理您期望的错误。

To belabour the point, though, documentation is the only way to tell what exceptions you should care about; in fact, any function can potentially raise any exception, even if it's just because signals may arrive and signal handlers may raise exceptions. You should not anticipate or handle those errors, however; you should just handle the errors you expect.