字符串转换$!

时间:2011-05-05 14:23:07

标签: ruby exception-handling

我正在尝试处理由以下代码引起的异常:

begin
  reader = CSV.open(ARGV[0],col_sep=";") 
rescue
  puts "exception: " + $!
  exit
end

不幸的是我无法正确显示消息,Ruby不解释$!作为字符串,似乎无法正确转换它:

$ ruby.exe fixcsv.rb csvfile
fixcsv.rb:11:in `+': can't convert ArgumentError into String (TypeError)
        from fixcsv.rb:11:in `rescue in <main>'
        from fixcsv.rb:8:in `<main>'

我真的不明白为什么会这样;以下教程显示了类似的代码,显然考虑了$!的正确字符串转换: http://ruby.activeventure.com/programmingruby/book/tut_exceptions.html

这与我没有明确设置异常类的事实有关吗?

3 个答案:

答案 0 :(得分:3)

begin
  reader = CSV.open(ARGV[0],col_sep=";") 
rescue Exception => e  
  puts "exception: #{e.message}"
end

答案 1 :(得分:3)

虽然我建议做fl00r做的事情(Exception => e),但如果你真的想要,你仍然可以使用$!

begin
  reader = CSV.open(ARGV[0],col_sep=";") 
rescue
  puts "exception: " + $!.message
  exit
end

答案 2 :(得分:2)

您甚至无需将.message添加到e,来自@ fl00r的示例:

begin
  reader = CSV.open(ARGV[0],col_sep=";") 
rescue Exception => e  
  puts "exception: #{e}"
end

Ruby会在异常.to_s上调用e。例外实施to_s,它们只是不实现to_str,这是"exception: " + $!尝试做的事情。

to_sto_str之间的区别在于前者意味着“你可以把我变成一个字符串,但我根本不像一个字符串”,而后者意味着“不仅仅是你可以把我变成一个字符串,但我非常喜欢一个字符串“。 <{1}}与to_s上的Jorg W Mittag's discussion非常值得一读。

相关问题