Exception Handling

Exceptions or Errors are not mistakes However, rather a feature therefore handling error is a way for us to become better programmers.

Error in JavaScript

JavaScript has a native error constructor function. Error

new Error("Error Message")
let error = true;

function a() {
  if (error) {
    return new Error("This is Error");
  }
  return "No Error";
}

console.log(a());
Error: This is Error

The error instance is created with new keyword. It does not do anything. It just show the Error message for programmers. I got “This is Error” message in console, but it is not an error.

What we need to do instead is to throw an error when we start throwing errors. JavaScript has throw keyword.

When we throw something the JavaScript which is running stops executing or at least stops executing it unless you are handling the through somehow which will go over.

Thus, throw new Error() is a proper error

let error = true;

function a() {
  if (error) {
    throw new Error("This is Error");
    return "THIS IS NEVER CALLED";
  }
  else{
    return "NO ERROR"
  }
}

console.log(a());
/Users/-/Desktop/1.js:88
    throw new Error("This is Error");
    ^

Error: This is Error

The throw new Error gets thrown and all stop the program. handled the Error somehow we have an error in our program and this throw statement is used to define our errors. So, during runtime, when we run our JavaScript, if the JavaScript read throw keyword, the execution of the current function will stop and control will be passed to the next part of the call stack.

  • throw with string
throw "err";
  • throw with boolean
throw "err";
^
err
(Use `node --trace-uncaught ...` to show where the exception was thrown)
throw true;
throw true;
^
true
(Use `node --trace-uncaught ...` to show where the exception was thrown)
  • throw with Error
throw Error;
throw Error;
^
[Function: Error] { stackTraceLimit: 10 }

General way: throw new Error()

Never execute next line

throw new Error();
console.log("Never executed");
  • console.log is not executed.

Three properties in Error Keyword

const userDefinedException = new Error("This is Error Message");

console.log(userDefinedException.name);
console.log(userDefinedException.message);
console.log(userDefinedException.stack);
Error
This is Error Message
Error: This is Error Message
    at Object.<anonymous> (/Users/jayjo/Desktop/1.js:84:30)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

Error Stack information

function errorStack() {
  const a = new Error("This is Error");
  return a;
}

console.log(errorStack());
Error: This is Error
    at errorStack (/Users/jayjo/Desktop/j.js:2:13)
    at Object.<anonymous> (/Users/jayjo/Desktop/j.js:7:13)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

This is a stack trace.

The JavaScript has built in constructors for errors.

errorStack().stack This is the command to show error stack.

You can also see Reference Error and syntax error. the errors you see that it automatically throws and has the throw keyword added upon it as soon as we have an error throw statement is used to generated are exceptions are errors. These errors are useful.

However, what if we wanted to handle them inside of our programs.

during our program when a throw statement is encountered an error is thrown our current function is going to stop and sometimes we might want to catch that error instead of stopping the entire program.

Event: 'uncaughtException'

fs = require("fs");

process.on("uncaughtException", (err, origin) => {
  fs.writeSync(
    process.stderr.fd,
    `Caught exception: ${err}\n` + `Exception origin: ${origin}`
  );
});

setTimeout(() => {
  console.log("This will still run.");
}, 500);

// Intentionally cause an exception, but don't catch it.
novalue;

console.log("This will not run.");
Caught exception: ReferenceError: novalue is not defined
Exception origin: uncaughtExceptionThis will still run.

This is a way your program does not stop running instead you handle these errors so that your program keeps running.

Leave a Reply

Your email address will not be published.

ANOTE.DEV