Reputation: 196
I would like to know the main goal to use Try & Catch in Javascript, below is the example i am achieving
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
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
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