Python 异常中错误编号的含义

8
在一次愚蠢的计算中捕获Python的OverflowError后,我查看了错误的args,发现它是一个包含整数作为第一个坐标的元组。我认为这是某种错误编号(errno)。然而,我找不到任何文档或参考资料。
示例:
try:
    1e4**100
except OverflowError as ofe:
    print ofe.args

## prints '(34, 'Numerical result out of range')'

你知道这种情况下34代表什么吗?你知道其他可能引起该异常的错误号码吗?


1
记录一下,1E400不能表示为Python浮点数的通常内部表示形式——双精度浮点数(double)。 - Gassa
另外一条记录,1e400 在 Python 2.7 中等于 inf(如 math.isinf(1e400) 所示)。 - Bach
1个回答

6

标准库中有一个叫做errno的模块:

该模块提供了标准的errno系统符号。每个符号的值是相应的整数值。名称和描述来自于linux/include/errno.h,应该是相当全面的。

/usr/include/linux/errno.h包括/usr/include/asm/errno.h,后者包含/usr/include/asm-generic/errno-base.h

me@my_pc:~$ cat /usr/include/asm-generic/errno-base.h | grep 34
#define ERANGE      34  /* Math result not representable */

现在我们知道34错误代码代表ERANGE。 1e4**100使用float_pow函数Object/floatobject.c进行处理。该函数的部分源代码如下:
static PyObject *
float_pow(PyObject *v, PyObject *w, PyObject *z)
{
    // 107 lines omitted

    if (errno != 0) {
        /* We do not expect any errno value other than ERANGE, but
         * the range of libm bugs appears unbounded.
         */
        PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
                             PyExc_ValueError);
        return NULL;
    }
    return PyFloat_FromDouble(ix);
}

因此,1e4**100会导致ERANGE错误(导致PyExc_OverflowError),然后由更高级别的OverflowError异常引发。

哦,太好了。我相信我的输出结果和你的完全一样。 - Bach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接