Home > Back-end >  What is the main use of Try & Catch in Javascript?
What is the main use of Try & Catch in Javascript?

Time:10-15

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");

CodePudding user response:

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.

CodePudding user response:

You don't want to check argument types in Javascript at all. It is what type systems like Typescript are for. They add clutter to your code, but not nearly as much as programming defensively the way you did in this contrived example.

You can also indirectly detect this kind of problems with unit tests if you really don't want a type system. For example it often happens that when the user inputs a number, you get a string, so your program needs to convert the input to a number at some point. You can test that step in a test suite. That outsources the type checking and leaves your code clean.

Catching exceptions is useful when you know you can programmatically act upon the information that an operation failed. For example you could retry, return a fallback value or ask the user for a different input.

The problem with exceptions is that they don't make the whole app crash, they make the current flow crash and if you don't do anything with them in production, the user will likely not know something went wrong: the app will appear to work but nothing will happen when they press that button or whatever. It's a terrible user experience.

Exceptions are OK for small units of code, when the consumer of a function is basically another function, it's better than returning some error code or whatnot (algebraic data types are also an option) but when you step back, when the consumer is the user, you want them to be caught and the error gracefully handled.

  • Related