问题描述
Python中是否有任何方法可以确定(内置)函数可能引发的异常?例如,文档()并没有说明以下事实:如果s不是有效格式化的int,它可能会引发ValueError。
Is there any way in Python to determine what exceptions a (built-in) function might raise? For example, the documentation (http://docs.python.org/lib/built-in-funcs.html) for the built-in int(s) says nothing about the fact that it might raise a ValueError if s is not a validly formatted int.
这是
推荐答案
告诉我们某些异常可能引发的异常的唯一方法是查看文档。 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.
这篇关于Python函数可能引发哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!