Is it better to wrap a Try/Catch inside a function (around your code) or is it better to wrap it around the function call?
Does it make a difference at all?
Consider the code below:
function catchErrorInside(){
try {
document.querySelector('#element-that-doesnt-exist').style.display = 'block';
} catch(e){console.log(e)}
}
catchErrorInside();
VERSUS
function catchErrorOutside(){
document.querySelector('#element-that-doesnt-exist').style.display = 'block';
}
try {
catchErrorOutside();
} catch(e){console.log(e)}
The error stacks are the same when I tested it. I did find that if I wrapped both the code inside the function AND the function call itself with Try/Catch blocks, the error that's thrown is from inside the function and not from the call.
I've tried looking around in SO and Google but couldn't find any real preferences or pros vs cons. My inkling is that depending on the complexity of the function, you may want to use Try/Catch inside the function as you may want to use try/catch blocks multiple times inside a given function.
generally exceptions handling should be placed at the beginning of a call stack (in ur example it's second case). If u place try/catch block inside some deep rooted function in your application, you take away caller's possibility to handle it in own preferred way (unless u would rethrow Error inside catch, but rethrowing is rarely needed). examples provided by u are senseless, because u log information, which is logged by console anyway without requirement to using catch for it.