Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda