octanium
octanium

Reputation: 31

Where does the exception gets caught when we are not using try catch in JavaScript

so I was learning about exception handling in javascript. Now I have seen 2 ways to throw an exception.

  1. Without a try/catch block.
  2. With a try/catch block.

With a try/catch block we can understand that the error will be caught inside the catch block, but when we are not using any block it gets caught in the next catch block on the call-stack. Since I have a single line in a single script ie throw new Error('someError') I can see the exception still gets caught, because the someError is there. Who catches this exception as I have not declared any try/catch ?.

(Also, like in C language the main() function gets pushed on to the stack, is it true for javascript too?)

Upvotes: 2

Views: 862

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

In most environments, there's a global exception handler that intercepts uncaught exceptions and (at least) dumps them out to some console or log. That's true in browsers and Node.js, for instance. In some environments (such as Node.js), an uncaught exception will terminate your program after being dumped to the log.

For example, consider this code:

function a() {
    throw new Error("a failed");
}

function b() {
    a();
}

function c() {
    b();
}

function d() {
    console.log("d");
}

function e() {
    console.log("e");
}

setTimeout(e, 100);
c();
d();

If you run that in a browser, c calls b which calls a which throws an exception. Since a doesn't catch it, it propagates to b. Since b doesn't catch it, it propagates to c. Since c doesn't catch it, it propagates to the environment, and gets "handled" (dumped to the console) by the global exception handler. Since that terminated the top-level execution of the code, d never gets called. But later, e gets called by the timer, because that timer callback was already scheduled before the .

If you run it in Node.js, the same happens but then the program gets terminated after the unhandled exception from calling c is dumped to the console, so e is never called despite being scheduled.

In contrast:

function a() {
    throw new Error("a failed");
}

function b() {
    a();
}

function c() {
    try {
        b();
    } catch (error) {
        console.log(`An error occurred: ${error.stack}`);
    }
}

function d() {
    console.log("d");
}

function e() {
    console.log("e");
}

setTimeout(e, 100);
c();
d();

There, the exception propagated from a to b to c, but then c "handled" it by reporting it to the user. Since c handled it, the main execution of the code wasn't interrupted so d gets called, and Node.js won't terminate the program so e gets called on Node.js where it didn't before.

Upvotes: 3

Related Questions