Javascript try…catch…else…finally like Python, Java, Ruby, etc

I know this is old, but here is a pure syntax solution, which I think is the proper way to go:

try {
    // Protected-block
    try {
        // Else-block
    } catch (e) {
        // Else-handler-block
    }
} catch(e) {
    // Handler-block
} finally {
    // Final-block
}

The code in Protected-block is executed. If the code throws an error, Handler-block is executed; If no error is thrown, Else-block is executed.

No matter what happened previously, Final-block is executed once the code block is complete and any thrown errors handled. Even if there’s an error in Handler-block or Else-block, the code in Final-block is still run.

If an error is thrown in the Else-block it is not handled by the Handler-block but instead by the Else-handler-block

And if you know that the Else-block will not throw:

try {
    // Protected-block
    // Else-block
} catch(e) {
    // Handler-block
} finally {
    // Final-block
}

Moral of the story, don’t be afraid to indent 😉

Note: this works only if the Else-handler-block never throws.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)