Exception Handling in JavaScript

Introduction

Exception handling is the process of responding to the occurrence of exceptions

Contents

  1. Try and Catch in JavaScript
  2. Exception Handling

1. Try and Catch in JavaScript

How can we catch errors in our programs in JavaScript

  1. try-catch block
  2. catch method

try-catch block

Anything inside of try block, if there is any errors then handle them in catch block. Catch block has a parameter about error.

function a() {
  try {
    let num = 1;
    let num2 = 2;
    novalue;
    return num + num2;
  } catch (error) {
    throw error;
  }
}
a();
      throw error
      ^

ReferenceError: novalue is not defined
    at a (/Users/jayjo/Desktop/j.js:23:5)
    at Object.<anonymous> (/Users/jayjo/Desktop/j.js:29:1)
    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

With Finally block

function a() {
  try {
    let num = 1;
    let num2 = 2;
    novalue;
    return num + num2;
  } catch (error) {
    throw error;
  } finally {
    console.log("It will finally run.");
  }
}
a();
It will finally run.
/Users/jayjo/Desktop/j.js:26
    throw error;
    ^

ReferenceError: novalue is not defined
    at a (/Users/jayjo/Desktop/j.js:23:5)
    at Object.<anonymous> (/Users/jayjo/Desktop/j.js:31:1)
    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

Even if there is an error in try block, the finally block will be executed.

Nested try-catch block

function a() {
  try {
    try {
      let num = 1;
      let num2 = 2;
      novalue;
      return num + num2;
    } catch (error) {
      throw new Error(error);
    }
  } catch (error) {
    console.log(error);
  }
}
a();
Error: ReferenceError: novalue is not defined
    at a (/Users/jayjo/Desktop/j.js:27:13)
    at Object.<anonymous> (/Users/jayjo/Desktop/j.js:33:1)
    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

These types of try catch blocks can be used to catch synchronous errors.

However, what if there is asynchronous code in try block?

function a() {
  try {
    setTimeout(function () {
      noValue;
    }, 10000);

    return true;
  } catch (error) {
    console.log(error);
  }
}
console.log(a());
true
/Users/jayjo/Desktop/j.js:22
      noValue;
      ^

ReferenceError: noValue is not defined
    at Timeout._onTimeout (/Users/jayjo/Desktop/j.js:22:7)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)

During 10 seconds, catch block can not catch the error. Thus, we have Async Error Handling.

2. 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