Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby rescue all exceptions except MyException

In Ruby, is it possible to rescue all exceptions except for a specified one?

like image 637
ma11hew28 Avatar asked Jan 25 '11 17:01

ma11hew28


People also ask

How do you rescue exceptions in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.

How does rescue work in Ruby?

For each rescue clause, the raised Ruby exception is compared against each parameter and the match succeeds if the exception in the clause is the same as or a superclass of the thrown exception. If the thrown Ruby exception does not match any of the specified exception types, the else block gets executed.

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.


1 Answers

begin

rescue MyException
  raise #to reraise the same exception without changing it
rescue Exception => e
  #do something with e
end
like image 173
Ken Bloom Avatar answered Sep 25 '22 13:09

Ken Bloom