2011-05-05 69 views
0

我試圖處理由此引起以下代碼的異常:

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

可惜我不能正確顯示的消息,林心如不解釋$!作爲字符串,似乎都不能正確地轉換它:

$ 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

雖然我會建議做fl00r做(Exception => e),你仍然可以使用$!,如果你真的想:

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

這是不真實的,因爲你不夠懶惰。 – 2011-05-05 23:34:36

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

你不需要在你的答案中執行'.message'。 – 2011-05-05 23:33:49

2

你甚至都不需要添加.messagee,從@ fl00r的例子:

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

什麼情況是,Ruby的異常上呼籲。例外情況實施to_s,他們只是不執行to_str,這是什麼"exception: " + $!試圖做。

to_sto_str之間的區別在於前者意味着「您可以將我變成字符串,但我根本不像字符串」,而後者的意思是「不僅可以將我變成字符串,但我非常喜歡一個字符串「。 Jorg W Mittag's discussionto_sto_str非常值得一讀。