rubyist icon indicating copy to clipboard operation
rubyist copied to clipboard

missing exceptions coding style

Open riffraff opened this issue 14 years ago • 1 comments

There should probably be some notes about how to handle exceptions, of the top of my mind

  • only use inline rescue to provide a default value, or nexting during iteration

    ary.map {|x| x.foo_bar rescue ... } #good ary.select {|x| x.foo_bar rescue next } #good do_something(...) rescue do_something_else(...) #bad

  • do not rescue Exception unless you really mean it

  • (arguable) do not create unnecessary exception objects (rescue => e)

  • if possible be strict in what you mean to catch (rescue SubSubCustomEx vs rescue Exception)

  • prefer shorthand syntax for rescue/ensure within methods. Write small methods so you don't overcatch stuff

    def foo() #good ... rescue ... ensure ... end def foo() #bad begin ... rescue ... ensure ... end end

  • do not swallow exceptions, or at least always log both error message and backtrace (although you may want to log them at an info level if they are "expected", e.g. network errors in a crawler)

  • if possible use techniques that can avoid you causing exceptions altogether, mostly NME comes to mind: ** respond_to? **try **Hash.new` with defaults

riffraff avatar Sep 08 '11 17:09 riffraff

+1

I love the do not rescue Exception unless you really mean it paragraph!

weppos avatar Sep 08 '11 17:09 weppos