2015-12-02 33 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