Nested Try/Catch

Contact Us or call 1-877-932-8228
Nested Try/Catch

Nested Try/Catch

We can nest try/catch/finally blocks to an arbitrary depth, depending on the need of our particular page or application. Consider the following example:

Code Sample:

ErrorsExceptions/Demos/nested-try-catch.html
---- C O D E   O M I T T E D ----

try {
    document.write("Outer try...<br/>");

    try {
        document.write("Inner try...<br/>");
        throw new Error("custom error");
    }
    catch (e) {
        document.write ("Inner catch caught error: " + e.message + "<br/>");
        throw e;
    }
    finally {
        document.write ("Inner finally...<br/>");
    }
} catch (e) {
    document.write ("Outer catch caught error: " + e.message + "<br/>");
} finally {
    document.write ("Outer finally...");
}

---- C O D E   O M I T T E D ----

Code Explanation

Our code contains an outer try/catch/finally block and an inner try/catch/finally block. We write to the screen the progression of the flow.

In the inner try we throw a custom error; the error is caught by the inner catch, after which the inner finally executes. The error propagates to, and is caught by, the outer catch, after which (finally) the outer finally executes.

We'll ask you to try out (no pun intended) error handing in the next exercise:

Next