Python函数可能引发哪些异常? [英] What exceptions might a Python function raise?

查看:114
本文介绍了Python函数可能引发哪些异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有任何方法可以确定(内置)函数可能引发的异常?例如,文档( http://docs.python.org/lib/内置int(s)的Built-in-funcs.html )并没有说明以下事实:如果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.

这是 re.compile()或任何给定的Python库调用是否引发异常?

推荐答案

告诉我们某些异常可能引发的异常的唯一方法是查看文档。 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函数可能引发哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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