When handling user input (in a JS library, not form text), it's easy to throw type-related errors, when a user supplies a non-function and you expected a function for instance. Suppose I have a function callFn
that takes a function and arguments to supply to it and evaluates the function or returns null if it fails to, I can either use try-catch or simply check that the input is a function before calling:
callFn(fn, args) {
return fn instanceof Function ? fn.apply(window, args) : null;
}
//vs
callFn(fn, args) {
var ret = null;
try {
ret = fn.apply(window, args);
}
catch (e) {
console.error(e) //Still display error for debugging
}
return ret;
}
What are the advantages and disadvantages of both ways? Am I correct in the following:
- Try-catch is slower, but not significantly so
- Try-catch can prevent optimization (see In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?, not sure if this still applies, can't find anything more recent)
- Try-catch will also handle any errors in the supplied function, which can be advantageous or disadvantageous depending on context
Any the biggest one and why I'm considering switching to try-catch
- If the user supplies an object with 10+ fields and many of those fields are functions to evaluate or objects to access, a single try-catch statement will suffice if the function returns the same for any error, but the error preventing way would have to 10 - 20
instanceof
/typeof
statements; thus try-catch is much more readable (and faster to write).
I'm asking since I hardly ever see try-catch, and was unsure if there is a better (good) reason for it to be bad practice.