Reputation: 229
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.
Upvotes: 2
Views: 443
Reputation: 239230
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
Upvotes: 2
Reputation: 106782
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
Upvotes: 4