为什么“引发异常”没有结果?

2024-04-24 10:50:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个1/0的表达式,很明显,它会出错:

try:
    1/0
except ZeroDivisionError as err:
    print(err)                      # this prints: division by zero

第二次尝试,用raise ZeroDivisionError替换1/0。。。你知道吗

try:
    raise ZeroDivisionError
except ZeroDivisionError as err:
    print(err)                      # this prints: (nothing)

它什么也没印出来。是不是一个来自raise的异常,和一般表达式一样?你知道吗

另外,如何更清楚地理解这种差异?你知道吗


Tags: by表达式as差异thisprintsdivisionraise
1条回答
网友
1楼 · 发布于 2024-04-24 10:50:27

所有异常都是BaseException的子类,因此所有内置异常都应该具有args属性。你知道吗

args:

The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.

当引发异常时,args元组或字符串可以作为第一个参数提供。你知道吗

try:
    raise ZeroDivisionError("error")
except ZeroDivisionError as err:
    print(err)  # prints "error"

来自except Exception as err:err是异常实例,当您print(err)时,实际上是在调用异常的__str__方法。大多数Exception class's ^{} return's ^{},因为这是BaseException的默认行为;如果异常类重写BaseException的__str__,则__str__将返回其他值。你知道吗

当您提出一个普通的ZeroDivisionError时,您没有提供args,并且ZeroDivisionError没有一个自定义的__str__方法,因此它在默认情况下打印了args,即a.k.aargs = None。你知道吗


至于你的问题:

Isn't an exception came from raise, same as the a general expression?

是的。它们是一样的。你知道吗

try:
    raise ZeroDivisionError("division by zero")
except ZeroDivisionError as err:
    print(err)       

这将输出与1/0相同的结果。你知道吗


我继续向前,在source code中挖掘。//(整数除法)和/(真除法)的错误消息略有不同。但它们基本上是这样定义的:

if (size_b == 0) {
        PyErr_SetString(PyExc_ZeroDivisionError,
                        "division by zero");
        return -1;
    }

size_b是除数。如您所见,1/0或任何被零除的除法都会产生一个ZeroDivsionErrorargs设置为"division by zero""integer division or modulo by zero",具体取决于您如何除法。你知道吗

相关问题 更多 >