It's not best practice. try/catch
you should use, and only use, for handling exceptional situations that interrupt the flow of code and break your ability to complete it. If you use it more generally, you wind up with a very powerful goto
-like structure with unwieldy use in your code.
try/catch is a harder structure to learn compared to if, else, while, etc., because it only really makes sense if you're working in a somewhat large code base, with modular library functions.
A simple example might be the function
var saveOrder = function(order) {
if(!order.confirmed) {
throw new Error("Please confirm you order.");
}
saveToMySQL(order);
};
//... somewhere else
try {
order = getOrderFromUser();
saveOrder(userOrder);
alert("Thank you for your order, continue shopping?");
}
catch(err) {
alert(err);
}
The points here are
saveOrder
throws because it cannot proceed
- try/catch is only used by the method that believes it can handle the exception
- if no exception happens, the code reads linearly and cleanly, and the following line never has to worry about whether the previous line succeeded