Robert
Robert

Reputation: 10380

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?

Upvotes: 29

Views: 74800

Answers (4)

Javier Tan
Javier Tan

Reputation: 81

According to the same source you are referencing, it mentions this:

If an inner try block does not have a corresponding catch block:

  1. it must contain a finally block, and
  2. the enclosing try...catch statement's catch block is checked for a match.

It seems to be that your code is missing a finally block since you chose to omit out the catch block.

Upvotes: 0

Andres R
Andres R

Reputation: 155

try {
    try {
        throw "error1";
    } catch (e1){
      console.log(e1)
    }
    throw "error2";
} catch( e2 ) {
    console.log( e2 );
}

>>> error1
>>> error2

In other words, the inner try-catch does not get picked up by the outer try-catch.

However, if you forget the inner catch, and close the inner try-catch with a 'finally' instead, your statement is valid and the inner error is passed on to the outer try-catch. I struggle to see why one would every do that in reality unless it's by accident. If you try something, your intention is to catch the error case I think.

    try {
        try {
            throw "error1";
        } finally  {
          console.log('final stuff')
        }
        throw "error2";
    } catch( e2 ) {
        console.log( e2 );
    }

>>> final stuff
>>> error 1

Upvotes: 3

Gaurav Kakkar
Gaurav Kakkar

Reputation: 358

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:

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1073978

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 );
}

Upvotes: 39

Related Questions