在以下代码中

begin
 raise StandardError, 'message'
 #some code that raises a lot of exception
rescue StandardError
 #handle error
rescue OtherError
 #handle error
rescue YetAnotherError
 #handle error
end

我想打印一条警告,指出错误的类型和错误信息,而不必在每个救援子句中添加print语句,例如
begin
 raise StandardError, 'message'
 #some code that raises a lot of exception
rescue StandardError
 #handle error
rescue OtherError
 #handle error
rescue YetAnotherError
 #handle error
???
 print "An error of type #{???} happened, message is #{???}"
end

最佳答案

begin
  raise ArgumentError, "I'm a description"
rescue => e
  puts "An error of type #{e.class} happened, message is #{e.message}"
end
打印:发生ArgumentError类型的错误,消息是我的描述

关于ruby - 如何显示 ruby 中的错误类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1461481/

10-12 13:15