在 Ruby 中,异常处理是一种用于处理运行时错误的机制。当程序执行过程中发生错误时,Ruby 会抛出异常,开发者可以使用异常处理机制来捕获并处理这些异常。以下是 Ruby 异常处理的基本语法和一些常见的用法:

异常基本语法
begin
  # 可能引发异常的代码块
  # ...
  # 异常会在这个块内被捕获
rescue SomeError => e
  # 处理 SomeError 异常的代码
  puts "Caught an exception: #{e.message}"
rescue AnotherError => e
  # 处理 AnotherError 异常的代码
  puts "Caught another exception: #{e.message}"
else
  # 如果没有异常发生时执行的代码块
ensure
  # 无论是否发生异常都会执行的代码块
end

抛出异常
def divide(x, y)
  raise "Cannot divide by zero" if y.zero?

  x / y
end

begin
  result = divide(10, 0)
  puts result
rescue StandardError => e
  puts "Error: #{e.message}"
end

自定义异常类
class MyCustomError < StandardError
  def initialize(message = "This is a custom error.")
    super
  end
end

begin
  raise MyCustomError, "Something went wrong!"
rescue MyCustomError => e
  puts "Caught a custom exception: #{e.message}"
end

使用 ensure 保证代码块
file = nil
begin
  file = File.open("example.txt", "r")
  # 读取文件内容等操作
rescue StandardError => e
  puts "Error: #{e.message}"
ensure
  file.close if file
end

异常对象的常用方法
begin
  # 可能引发异常的代码块
  # ...
rescue StandardError => e
  puts "Exception class: #{e.class}"
  puts "Exception message: #{e.message}"
  puts "Backtrace:\n#{e.backtrace.join("\n")}"
end

这些是 Ruby 中异常处理的一些基本用法。在实际编程中,根据具体的需求和情境,可以选择合适的异常类进行捕获和处理。异常处理是确保程序健壮性和可靠性的重要机制之一。如有其他问题,请随时提问。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13440/Ruby