missing exceptions coding style #5

Open
riffraff opened this Issue Sep 8, 2011 · 1 comment

Projects

None yet

2 participants

@riffraff
riffraff commented Sep 8, 2011

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

@weppos
Owner
weppos commented Sep 8, 2011

+1

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment