Appearance
Error Propagation
If an error occurs in the code and is not caught by try ... catch, where will the program execution flow jump to?
javascript
function getLength(s) {
return s.length;
}
function printLength() {
console.log(getLength('abc')); // 3
console.log(getLength(null)); // Error!
}
printLength();
If an error occurs within a function and is not caught by that function, the error will be thrown to the outer calling function. If the outer function also does not catch it, the error will continue to propagate up the function call chain until it is caught by the JavaScript engine, at which point code execution will terminate.
Therefore, we do not need to catch errors in every single function; we just need to perform a unified catch at appropriate places to handle all errors:
javascript
function main(s) {
console.log('BEGIN main()');
try {
foo(s);
} catch (e) {
console.log('An error occurred: ' + e);
}
console.log('END main()');
}
function foo(s) {
console.log('BEGIN foo()');
bar(s);
console.log('END foo()');
}
function bar(s) {
console.log('BEGIN bar()');
console.log('length = ' + s.length);
console.log('END bar()');
}
main(null);
When the bar() function is passed a null argument, the code will throw an error. This error will be propagated to the calling function foo(), which does not have a try ... catch statement, so the error will continue to propagate to the calling function main(). The main() function has a try ... catch statement, so the error will ultimately be handled there.
As for where it is most appropriate to catch errors, it depends on the specific situation.