I'm trying to understand the syntax of Ruby-exceptions.
I found this example:
begin
puts "Running with b=#{ b }"
exception_if(b)
puts "After possible exception"
rescue ArgumentError => e
puts "An error occured: #{ e }!"
ensure
puts "Always excuted, no matter what."
end
Source: Wiki-Books
"ArgumentError" is the expection-type, which the rescue-branch shall catch? "e" is the reference-variable?
I'm I right there?
Then I found this snippet and that confused me then completely:
begin
@product = Product.find(params[:id])
rescue => e
redirect_to root_path
end
Where's the first part before the arrow (=>)?
Can someone explain me, how the two snippets are meant?
Edit: The second snippet is rescuing errors that are instances of StandardError, in a console:
begin
raise NoMethodError
rescue => e
puts e.inspect
end
#<NoMethodError: NoMethodError>
The exception object is assigned to the e variable. This can also read
rescue StandardError => e
The first snippet is initially rescue-ing one specific error, if another type of error is raised the ensure block will always be executed and then the method is exited.
As a general rule of thumb, you should only capture exceptions your program can recover from. If the program experiences an unknown exception crash it and fix the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With