为什么在处理异常后会有“无”值?

问题描述

我尝试运行此简单代码以尝试处理ZeroDivisionError异常

def test(n):
    try:
        return 10 / n
    except ZeroDivisionError:
        print('Can\'t divide by 0')

print(test(0))

输出

Can't divide by 0
None

处理异常后为什么没有None值?

解决方法

因为您没有从函数中返回值。

该异常由表达式10 / n引发,该表达式在return语句之前求值。 因此,决不会执行return语句。

您必须定义在抛出异常时函数应返回的内容。

像这样:

def test(n):
    try:
        return 10 / n
    except ZeroDivisionError:
        print('Can\'t divide by 0')
    return -1 # DIV/0 should return -1

print(test(0))

或者像这样:

def test(n):
    try:
        return 10 / n
    except ZeroDivisionError:
        print('Can\'t divide by 0')
        return -1 # DIV/0 should return -1

print(test(0))

请参阅:https://onlinegdb.com/By2AVSvEv