gpt4 book ai didi

ruby - 为什么 `rescue`默认抓不到 `StandardError`以外的异常类?

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:15 24 4
gpt4 key购买 nike

为什么 Ruby 被设计为仅通过 rescue 隐式处理 StandardError 异常?对于其他异常,为什么我们需要用 rescue 显式地放置它们?

begin
#codes here which may generates exceptions
rescue
#codes to handle some thing which really needed to be done when exceptions there
end

谁能帮我理解它的核心?

最佳答案

当你没有明确给出类型时,默认行为 rescue StandardError 的原因是你通常不想在你的程序中处理非 StandardError,至少在没有明确提及它们的情况下.几个典型的非 StandardError 异常是;

LoadError
NotImplementedError
SyntaxError

通常,您想了解程序中丢失的脚本文件、未实现的方法和代码中的语法错误,而不是在异常代码中意外处理/忽略它们。

您还可以(不推荐)使用替代语法捕获任何异常

rescue Exception => e  

关于ruby - 为什么 `rescue`默认抓不到 `StandardError`以外的异常类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com