Short notation for coffeescript try/catch

Juve picture Juve · Aug 25, 2013 · Viewed 17.5k times · Source

I sometimes write code like:

try doSomething()
catch e
  handleError e

which is not what nice and clean coffeescript code should look like.

Is there a way to write:

try doSomething()
catch e handleError e   #<-- will not compile

This would save me about 33% of the lines of code in my try/catch statements ;)

Answer

Juve picture Juve · Aug 25, 2013

Writing try/catch one-liners works like if-then one-liners or loop one-liners using the then keyword:

try doSomething()
catch e then handleError e
finally cleanUp()

You can even have it on a single line if you like:

try doSomething() catch e then handleError e finally cleanUp()