how to combine rescue multiple exceptions in ruby on rails?

Viewed 2164

is it possible to combine multiple rescue statements into one in ruby on rails.

begin
   //do something 
  rescue ArgumentError => e
      e.message
  rescue NameError => e
      e.message
  rescue StandardError => e
      e.message
end

combined to something like below

rescue ArgumentError, NameError, StandardError => e
      e.message
2 Answers

That will work. You'll want to consider how and whether you expect this code to change in the future, and whether this format is conducive to that change.

This is also a good candidate for writing the code and seeing what happens (especially if you can reproduce the appropriate behavior with a test), even if only in the rails console. You might find a faster feedback loop there.

You don't want to add separate exceptions for those. Because ArgumentError and NameError are under StandardError.

Here is the exceptions hierarchy.

- NoMemoryError
- ScriptError
    - LoadError
    - NotImplementedError
    - SyntaxError
- SecurityError
- SignalException
    - Interrupt
- StandardError (default for `rescue`)
    - ArgumentError
        - UncaughtThrowError
    - EncodingError
    - FiberError
    - IOError
        - EOFError
    - IndexError
        - KeyError
        - StopIteration
    - LocalJumpError
    - NameError
        - NoMethodError
    - RangeError
        - FloatDomainError
    - RegexpError
    - RuntimeError (default for `raise`)
    - SystemCallError
        - Errno::*
    - ThreadError
    - TypeError
    - ZeroDivisionError
- SystemExit
- SystemStackError
- fatal (impossible to rescue)
Related