2015-12-02 73 views
1

我封閉了一些代碼在beginrescueend塊:Ruby的異常處理

begin 
    ... 
rescue StandardError => e 
    puts("Exception #{e} occurred") 
    puts("Copying script to error folder.") 
    FileUtils.cp("Demo.rb", "C:/Ruby/Failure") 
end 

我不知道如何,如果沒有異常拋出這樣我可以在我的腳本複製到一個成功執行一段代碼夾。任何幫助,將不勝感激。

+0

你不只是遵循複製你的腳本方法你#CODE,所有的開始......救援塊內? – Phil

+0

你會......不知道爲什麼我沒有想到這一點。謝謝您的幫助。 – jackfrost5234

+0

'StandardError'是默認的,你可以直接寫'rescue => e' – Stefan

回答

2

你在想的異常錯誤。

異常的重點在於代碼的主體繼續進行,就好像沒有拋出異常一樣。 所有您的begin塊內的代碼是已經執行,就像沒有任何異常被拋出一樣。異常會中斷正常的代碼流,並阻止後續步驟的執行。

你應該把你的文件拷貝東西begin塊內:

begin 
    #code... 
    # This will run if the above "code..." throws no exceptions 
    FileUtils.cp("Demo.rb", "C:/Ruby/Success") 
rescue StandardError => e 
    puts("Exception #{e} occurred") 
    puts("Copying script to error folder.") 
    FileUtils.cp("Demo.rb", "C:/Ruby/Failure") 
end 
4

你可以使用else只運行,如果沒有異常代碼:

begin 
    # code that might fail 
rescue 
    # code to run if there was an exception 
else 
    # code to run if there wasn't an exception 
ensure 
    # code to run with or without exception 
end 
+0

'else'似乎更合適。否則,'rescue'可能會意外地挽救'FileUtils.cp(「Demo.rb」,「C:/ Ruby/Success」)引發的異常。 – Stefan