Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda