【问题标题】:Meaning of error numbers in Python exceptionsPython异常中错误号的含义
【发布时间】:2014-04-09 07:31:47
【问题描述】:

在经过一些愚蠢的计算后,我发现了 Python 的 OverflowError,检查了错误的 args,发现它是一个包含整数作为其第一个坐标的元组。我认为这是某种错误号 (errno)。但是,我找不到任何文档或参考。

例子:

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

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

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

【问题讨论】:

  • 作为记录,1E400 不能表示为double,这是 Python 浮点数的通常内部表示。
  • 对于另一条记录,1e400 在 python 2.7 中等于 inf(如 math.isinf(1e400) 所示)。

标签: python errno overflowexception


【解决方案1】:

标准库中有一个模块叫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 使用来自Object/floatobject.cfloat_pow function 进行处理。该函数的部分源码:

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 异常。

【讨论】:

  • 哦,太好了。我相信我的输出和你一样。
猜你喜欢
  • 2018-07-24
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
相关资源
最近更新 更多