Search code examples
rubyexceptionjruby

How to figure out what exception to catch in Ruby


I was given some code that keeps getting an exception raised from a jRuby library. The code only handles certain exceptions but it misses the one I keep getting.

Is there a way I can figure out how to capture that specific exception without digging into the Library code?


Solution

  • At the point where your exception causes the program to exit, you should be shown the type of exception being raised.

    For example, I've bolded the type of exception as reported by IRB in the following example:

    irb(main):001:0> def do_it(a,b); end; do_it(3,4,5)
    ArgumentError: wrong number of arguments (given 3, expected 2)
      from (irb):1:in `do_it'
      from (irb):1
      from /Users/meagar/.rbenv/versions/2.3.1/bin/irb:11:in `'

    Based on this, I would know I needed to handle ArgumentError.

    Failing that, you can catch all exceptions, use a debugger in your exception handler to inspect the caught exception and figure out its type, and then replace the catch-all with the correct exception type.