Python异常中的错误号码含义

8 投票
1 回答
1556 浏览
提问于 2025-04-18 01:59

在进行一些愚蠢的计算后,我捕获到了Python的OverflowError错误。我查看了这个错误的args,发现它是一个元组,里面的第一个元素是一个整数。我猜这可能是某种错误编号(errno)。不过,我找不到任何相关的文档或参考资料。

示例:

try:
    1e4**100
except OverflowError as ofe:
    print ofe.args

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

你知道在这个情况下34是什么意思吗?你知道这个异常还有其他可能的错误编号吗?

1 个回答

6

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

这个模块提供了标准的错误号符号。每个符号的值对应一个整数。它的名称和描述是从 linux/include/errno.h 里借来的,基本上涵盖了所有常见的错误。

/usr/include/linux/errno.h 包含了 /usr/include/asm/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 异常就会被抛出。

撰写回答