try {} without catch {} possible in JavaScript?

pimvdb picture pimvdb · Apr 23, 2011 · Viewed 80.5k times · Source

I have a number of functions which either return something or throw an error. In a main function, I call each of these, and would like to return the value returned by each function, or go on to the second function if the first functions throws an error.

So basically what I currently have is:

function testAll() {
    try { return func1(); } catch(e) {}
    try { return func2(); } catch(e) {} // If func1 throws error, try func2
    try { return func3(); } catch(e) {} // If func2 throws error, try func3
}

But actually I'd like to only try to return it (i.e. if it doesn't throw an error). I do not need the catch block. However, code like try {} fails because it is missing an (unused) catch {} block.

I put an example on jsFiddle.

So, is there any way to have those catch blocks removed whilst achieving the same effect?

Answer

kennebec picture kennebec · Apr 23, 2011

A try without a catch clause sends its error to the next higher catch, or the window, if there is no catch defined within that try.

If you do not have a catch, a try expression requires a finally clause.

try {
    // whatever;
} finally {
    // always runs
}