Ruby 中的 try...catch
    
    
            Nurudeen Ibrahim
    2023年1月30日
    
    Ruby
    Ruby Exception
    
 
异常是在程序执行期间发生的不希望发生的事件。一个例子是当程序试图将一个数字除以零时出现 ZeroDivisionError。抢救异常是一种优雅地处理它的方法,因此它不会使程序崩溃。
Ruby 中的异常通常由两个子句组成,begin 和 rescue。begin 子句相当于 Python 或任何其他类似编程语言中的 try,而 rescue 相当于 catch。下面是语法。
begin
  # do something that might cause an exception
rescue
  # handle the exception here
end
让我们编写一个简单的程序,在给定商品的销售价格和成本价格的情况下计算利润百分比。
示例代码:
def profit_percentage(selling_price, cost_price)
  profit = selling_price - cost_price
  "#{(profit.fdiv(cost_price) * 100)}%"
end
puts profit_percentage(30, 20)
puts profit_percentage(30, nil)
输出:
50.0%
nil can't be coerced into Integer (TypeError)
正如我们在上面的输出中看到的,第二次调用 profit_percentage 引发了错误,因为我们将 nil 作为 cost_price 传递。现在让我们来说明一下我们可以挽救这个异常的不同方法。
使用 Ruby 中的通用错误消息进行救援
使用通用错误消息进行救援并不总是有帮助,因为它不会揭示异常的根本原因。
示例代码:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    "#{(profit.fdiv(cost_price) * 100)}%"
  rescue
    "An unknown error occurred."
  end
end
puts profit_percentage(30, nil)
输出:
An unknown error occurred.
使用 Ruby 异常中的消息进行救援
如果你对引发的异常类型不感兴趣,而只对错误消息感兴趣,则此方法会派上用场。
示例代码:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    "#{(profit.fdiv(cost_price) * 100)}%"
  rescue => e
    e
  end
end
puts profit_percentage(30, nil)
输出:
nil can't be coerced into Integer
在 Ruby 中抢救特定类型的异常
如果你只对处理特定类型的异常感兴趣,这将很有帮助。
示例代码:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    "#{(profit.fdiv(cost_price) * 100)}%"
  rescue TypeError
    "An argument of invalid type was detected"
  end
end
puts profit_percentage(30, nil)
输出:
An argument of invalid type was detected
此外,值得一提的是,还有另一个可选子句 ensure,这在你总是需要执行某些代码而不管是否引发异常的情况下可能会有所帮助。
示例代码:
def profit_percentage(selling_price, cost_price)
  begin
    profit = selling_price - cost_price
    puts "#{(profit.fdiv(cost_price) * 100)}%"
  rescue => e
    puts e
  ensure
    puts "Done calculating profit %"
  end
end
profit_percentage(30, 20)
profit_percentage(30, nil)
输出:
50.0%
Done calculating profit %
nil can't be coerced into Integer
Done calculating profit %
如上面的输出所示,ensure 子句中的代码在 profit_percentage 的两个调用中都被触发。该子句通常用于在执行某些文件操作后需要关闭文件时,无论是否发生异常。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe