Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the shortest way to silently ignore a Ruby exception

I'm looking for something like this:

raise Exception rescue nil 

But the shortest way I've found is this:

begin   raise Exception rescue Exception end 
like image 310
fguillen Avatar asked Feb 23 '11 10:02

fguillen


People also ask

How do I ignore an error in Ruby?

To ignore additional errors, use the exceptions. ignore configuration option. The gem will ignore any exceptions matching the string, regex or class that you add to exceptions.

What does rescue do 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 do I ignore an exception in catch?

To ignore an exception in Java, you need to add the try... catch block to the code that can throw an exception, but you don't need to write anything inside the catch block.

Does Ruby have exception handling?

Ruby provide a nice mechanism to handle exceptions. 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.


2 Answers

This is provided by ActiveSupport:

suppress(Exception) do    # dangerous code here end 

http://api.rubyonrails.org/classes/Kernel.html#method-i-suppress

like image 93
Jonathan Swartz Avatar answered Oct 05 '22 19:10

Jonathan Swartz


def ignore_exception    begin      yield      rescue Exception    end end 

Now write you code as

ignore_exception { puts "Ignoring Exception"; raise Exception; puts "This is Ignored" } 
like image 30
Zimbabao Avatar answered Oct 05 '22 20:10

Zimbabao