Error Handling
Exception Handling (Error Handling)
begin-rescue
(try-catch
).
# basic syntax begin # ... rescue => e # ... end # rescuing specific Error class name begin # ... rescue ArgumentError => e # ... end
Full Chain
begin # may raise an exception rescue AnException # exception handler rescue AnotherException # exception handler else # other exceptions ensure # always executed end
When/When NOT to Use
Exceptions shouldn't be used for validations.
You shouldn't traverse the stack for validations in general.
What you should NOT be doing
- X is top level and can handle everything.
- X calls Y. Y calls Z.
- Z performs validations and does something after that, raising an exception if validation failed.
What you should be doing instead
- X calls Y. Y calls V and X.
- V performs validations and returns result based on if the operation was valid.
- Y doesn't get to call X if V said the thing was invalid.
- Y propagates the invalidness or the successful result to X
- X does what it would have done with
if
/else
on the validity, rather thanrescue
Exception Chaining
In Ruby, rescuing multiple exceptions are easy.
begin ... rescue Exception1, Exception2 ... rescue Exception1 ... rescue Exception2 ... end