Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript nested try exception

I am reading up on JavaScript exceptions:

You can nest one or more try...catch statements. If an inner try...catch statement does not have a catch block, the enclosing try...catch statement's catch block is checked for a match.

I think I understood it correctly and wrote this test code as follows:

try {

    try {
        throw "error";
    }

} catch( e ) {

    console.log( e );

}

But got this error:

Uncaught SyntaxError: Missing catch or finally after try

I know it clearly says that I am missing a catch or finally but the JavaScript documentation says my code should be valid or am I misunderstanding?

like image 852
Robert Rocha Avatar asked Mar 08 '15 17:03

Robert Rocha


2 Answers

The quoted text is quite misleading because it says "if an inner try..catch doesn't have a catch block" which doesn't make any sense. It should just be "if an inner try doesn't have...".

In JavaScript, you can't just have a try on its own; it has to have a catch, finally, or both. So the scenario that quote is referring so isa try/catch containing a try/finally (not another try/catch):

try {
    try {
        throw "error";
    }
    finally {
    }
} catch( e ) {
    console.log( e );
}
like image 170
T.J. Crowder Avatar answered Sep 18 '22 05:09

T.J. Crowder


It is specified here: (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/try...catch)

The try statement consists of a try block, which contains one or more statements, and at least one catch clause or a finally clause, or both. That is, there are three forms of the try statement:

like image 36
Gaurav Kakkar Avatar answered Sep 19 '22 05:09

Gaurav Kakkar