30

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
vinhboy
  • 8,542
  • 7
  • 34
  • 44
fguillen
  • 36,125
  • 23
  • 149
  • 210

3 Answers3

37

This is provided by ActiveSupport:

suppress(Exception) do
   # dangerous code here
end

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

Jonathan Swartz
  • 1,913
  • 2
  • 17
  • 28
  • 1
    +1 for the clean solution, but I prefer no-dependencies solution. – fguillen Oct 01 '13 at 10:54
  • 3
    I would suggest replacing `Exception` for `StandardError` since [it's not a good practice to rescue `Exception`](https://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby). – aelesbao Jul 03 '17 at 13:07
  • clean? it's the dumbest method ever in my opinion, it rewrites the same thing in another way but it's not even shorter than a simple `rescue Exception; end` in most cases – Pere Joan Martorell Feb 16 '21 at 02:39
  • Shorter is not always better. In this case the intention is much clearer than scrolling to the end of the block and seeing the "rescue end". – Jonathan Swartz Feb 17 '21 at 04:08
28
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" }
Paweł Gościcki
  • 9,066
  • 5
  • 70
  • 81
Zimbabao
  • 8,150
  • 3
  • 29
  • 36
  • 1
    Note (because I misunderstood at first): This "ignores" the exception in the sense that everything continues after skipping the rest of whatever is between the begin and the rescue the exception. What it *doesn't* do is entirely ignore the exception in the sense that it continues doing what it was doing between the begin and the rescue. – cesoid Mar 14 '17 at 15:48
13

Just wrap the left-hand side in parenthesis:

(raise RuntimeError, "foo") rescue 'yahoo'

Note that the rescue will only happen if the exception is a StandardError or a subclass thereof. See http://ruby.runpaint.org/exceptions for more info.

Saad Malik
  • 1,598
  • 1
  • 18
  • 20