如何从`require'中解救:没有这样的文件加载到ruby中?

时间:2010-03-17 09:06:23

标签: ruby exception-handling require

我正试图从``require'中解救:没有这样的文件按顺序加载到ruby`中 提示用户指定-I标志,以防他忘记这样做。 基本上代码如下:

begin
  require 'someFile.rb'
rescue
  puts "someFile.rb was not found, have you"
  puts "forgotten to specify the -I flag?"
  exit
end

我预计rescue部分会在未找到someFile.rb的情况下接管执行,但我的假设是错误的。

2 个答案:

答案 0 :(得分:55)

没有参数的

救援只能救出 StandardError LoadError (由未找到的文件引发)不是 StandardError ,而是 ScriptError (请参阅http://blog.nicksieger.com/articles/2006/09/06/rubys-exception-hierarchy)。因此,您必须明确地拯救 LoadError ,如MBO所示。

答案 1 :(得分:49)

您必须明确定义要从中拯救的错误。

begin
  require 'someFile.rb'
rescue LoadError
  puts "someFile.rb was not found, have you"
  puts "forgotten to specify the -I flag?"
  exit
end