except 与 raise 异常

except versus raise exception

提问人:user11849 提问时间:10/28/2023 更新时间:10/28/2023 访问量:42

问:

我正在观看 Python 计算机科学和编程导论,我无法很好地理解有关异常的第 7 类主题。提供了两个示例代码

    try:
    a = int(input("Tell me one number: "))
    b = int(input("Tell me another number: "))
    print("a/b = ", a/b)
except:
    print("Bug in user input.")


try:
    a = int(input("Tell me one number: "))
    b = int(input("Tell me another number: "))
    print("a/b = ", a/b)
    print("a+b = ", a+b)
except ValueError:
    print("Could not convert to a number.")
except ZeroDivisionError:
    print("Can't divide by zero")
except:
    print("Something went very wrong.")

def get_ratios(L1, L2):
    """ Assumes: L1 and L2 are lists of equal length of numbers
        Returns: a list containing L1[i]/L2[i] """
    ratios = []
    for index in range(len(L1)):
        try:
            ratios.append(L1[index]/L2[index])
        except ZeroDivisionError:
            ratios.append(float('nan')) #nan = Not a Number
        except:
            raise ValueError('get_ratios called with bad arg')
        else:
            print("success")
        finally:
            print("executed no matter what!")
    return ratios
    
print(get_ratios([1, 4], [2, 4]))

我试过了

except ValueError:
                print('get_ratios called with bad arg')

在第二段代码中的函数内部,但它不起作用。总的来说,我不太明白这两件事之间的区别。我试图在网上找到解释,并阅读了一些投掷和接球的类比,但它并没有为我澄清太多。

你们中的任何人都能用示例代码进行解释,以便我可以查看输出并尝试理解这一点吗?

谢谢,非常感谢

Python 异常 错误处理

评论

0赞 Thierry Lathuille 10/28/2023
您是否知道 a bare 可以捕获所有异常?except:
0赞 user19077881 10/28/2023
raise与条件(如 x < 0)一起使用,沿 not 作为块的一部分。然后,它将停止代码执行。if condition: raise ValueError('message')try_ except
0赞 roganjosh 10/28/2023
区别很简单。 将导致程序崩溃。 ON 将继续运行raiseprint()except
1赞 chepner 10/29/2023
raise不会使程序崩溃;它引发了异常。如果程序仍未捕获异常,则解释器将退出并进行回溯。

答:

0赞 dungxibo123 10/28/2023 #1

except:
    raise ValueError('get_ratios called with bad arg')

在所有其他异常情况下引发 ValueError

在本例中,当您使用第二个代码时,它会引发一个 not, .但是,TypeError 不同于 “成功” 的源代码,也不同于 ,但它是 .因此,代码将引发 .(因为你从来不会这样做)。TypeErrorValueErrorZeroDivisionErrorExceptionTypeErrorTypeError

对于第一个版本,代码并不介意你是否是哪种,代码总是会跑到行中。尝试用以下代码替换该术语,看看不同的ratios.append(L1[index]/L2[index])Errorraise ValueError('get_ratios called with bad arg')

def get_ratios(L1, L2):
    """ Assumes: L1 and L2 are lists of equal length of numbers
        Returns: a list containing L1[i]/L2[i] """
    ratios = []
    for index in range(len(L1)):
        try:
            ratios.append(L1[index]/L2[index])
        except ZeroDivisionError:
            ratios.append(float('nan')) #nan = Not a Number
        except TypeError:
            print("Your code ran in to the TypeError")
        except ValueError:
            print("something")

        else:
            print("success")
        finally:
            print("executed no matter what!")
    return ratios

-----------

def get_ratios(L1, L2):
    """ Assumes: L1 and L2 are lists of equal length of numbers
        Returns: a list containing L1[i]/L2[i] """
    ratios = []
    for index in range(len(L1)):
        try:
            ratios.append(L1[index]/L2[index])
        except ZeroDivisionError:
            ratios.append(float('nan')) #nan = Not a Number
        except TypeError:
            print("Your code ran in to the TypeError")
        except:
            print("something")

        else:
            print("success")
        finally:
            print("executed no matter what!")
    return ratios