4 ms·
Due to asynchronous nature of JavaScript it's basically impossible to use "one big try/catch". Code that is invoked via setTimeout executes with an empty stack
by jakub_g 13y ago
Due to asynchronous nature of JavaScript it's basically impossible to use "one big try/catch". Code that is invoked via setTimeout executes with an empty stack so something like
try { setTimeout(foo, 1000) } catch (ex) { ... }
won't be caught here if foo throws. In some DOM APIs there are 'onerror' handlers (like XHR), in NodeJS the convention is to have an "error" first parameter in the callback (which is null if there's no error).
Also try-catch generates additional scope object inside the catch clause hence it's a bit more expensive than just doing a function call.
Generally try-catch makes sense in JavaScript only locally when executing some external synchronous code that is known to throw exceptions.