Saoud ElTelawy
Saoud ElTelawy

Reputation: 196

What is the main use of Try & Catch in Javascript?

I would like to know the main goal to use Try & Catch in Javascript, below is the example i am achieving

  1. Should I need to let the program stop in case of error?
  2. Why In programming I need to my application to continue running however there is an error?
  try {
    if (typeof a != "number") {
      throw new ReferenceError("The First argument is not a number");
    } else if (typeof b != "number") {
      throw new ReferenceError("The Second argument is not a number");
    } else {
      console.log(a + b);
    }
  } catch (error) {
    console.log("Error:", error.message);
  }
}

addTwoNums("10", 100);
console.log("It still works");

Upvotes: 0

Views: 172

Answers (2)

Aadarsh kumar Singh
Aadarsh kumar Singh

Reputation: 11

The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct

Upvotes: 1

Gamaray
Gamaray

Reputation: 151

There are some things in java that require try and catch statements to function, for instance if you wanted to read a file java will prevent you from doing so unless error catching is used.

In your example whilst there is no harm in using try, it is simply unnecessary as there is no variability in the success of your function. Also, since there is no need to stop the program if the arguments are invalid, instead of throwing errors it might be preferable to instead halt the operation and return a warning.

Upvotes: 0

Related Questions