Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Does it matter if I wrap a Try/Catch around code inside a function or around the function call?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!