2

I enclosed some code in a begin rescue end block:

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

I'm not sure how to execute a bit of code if no exceptions are thrown so I can copy my script to a success folder. Any help would be appreciated.

3
  • Would you not just follow your #code with the methods to copy your script, all within the begin ... rescue block? Commented Dec 2, 2015 at 15:19
  • That you would.. Not sure why I didn't think of that. Thanks for the help. Commented Dec 2, 2015 at 15:22
  • StandardError is the default, you can just write rescue => e Commented Dec 2, 2015 at 17:08

2 Answers 2

4

You could use else to run code only if there wasn't an exception:

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
Sign up to request clarification or add additional context in comments.

1 Comment

else seems more appropriate. Otherwise, rescue could accidentally rescue an exception that was raised by FileUtils.cp("Demo.rb", "C:/Ruby/Success").
2

You're thinking about exceptions incorrectly.

The whole point of exceptions is that the main body of your code proceeds as though no exceptions were thrown. All of the code inside your begin block is already executing as though no exceptions were thrown. An exception can interrupt the normal flow of code, and prevent subsequent steps from executing.

You should put your file copy stuff inside the begin block:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.