Javascript - How to make a try catch and finally statement

In JavaScript, you can use try, catch and finally statements to handle exceptions. Below is an example of how you can use a try-catch statement in JavaScript:

try {
  // code that may throw an exception
  throw 'this is an exception';
  console.log('this will not be hit');
} catch (error) {
  // code to handle the exception
  console.log(error);
} finally {
  // code to be executed regardless of the try / catch result
  console.log("and finally...");
}

In the above both "this is an exception" and "and finally.." will be written to the console, but not "this will not be hit". Inside the try clause is the code that might throw an exception, if an exception is thrown the catch clause is triggered. The finally clause is always triggered, regardless of the catch block being triggered or not.

You can check the type of exception using instanceof:

try {
  throw new TypeError('type error!!');
} catch (error) {
  if(error instanceof TypeError) {
    console.log("Type Error Occurred");
  } else if(error instanceof string) {
    console.log("string Error Occurred");
  }
}

In other programming languages you might be able to set multiple catch statement with different types, in javascript when you throw something it is passed to the catch statement. You can throw an int, a String or a TypeError as seen in the above, so they are not necessarily "exceptions". In order to determine what was thrown you can check the type of it as seen in the above.

That is all!

I hope you found this helpful, please leave a comment down below if you have any questions or even a better answer!