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

88
Vistas
What is the point of finally in a try..catch?

Is there any reason to put code in a finally block as opposed to just having code after the try...catch statement. Surely in both cases the code gets run anyway

try {
   something();
} catch (error) {
   error_handling_with(error);
}
// code here gets executed whether in finally clause or not.
finally_something();

Is there any place where finally is essential after try...catch? I can see it has a use in Promises, just not here.

almost 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

finally basically runs even if you have an early-return from try-catch or even if you don't handle the error in the try-catch. Here is an example I like:

function myFunction() {
  try {
    console.log('inside "try"');
    return
  } finally {
    console.log('inside "finally"');
  }

  console.log("after try-finally");
}

myFunction()

When you run myFunction(), it will print the following:

inside "try"
inside "finally"

Since you returned from try, it didn't execute any instructions after the try-finally block. But, Javascript did execute the finally block.

almost 4 years ago · Santiago Trujillo Denunciar

0

I think you have received the correct technical answer for this. However, if you are asking for practical usage, one situation is when you want to close a connection in any case. Here is a pseudo-code to explain:

openConnection();

try {
  DoSomething();
  return;
} catch (anomaly) {
  handleAnomaly();
} finally {
  closeConnection();
}

See in the above case, you close the connection in every case whether there is a handled exception, un-handled exception or happy flow, your connection will be closed and that too without duplication of code.

almost 4 years ago · Santiago Trujillo Denunciar

0

Catch/Finally are optional, the only rule is that 1 of them must always exist.

Finally exists so that code can always be run, disregarding whether or not an error was caught or not.

I would argue that in some cases they are added when they're not needed, but it helps readability, in other cases it might just be a habit.

almost 4 years ago · Santiago Trujillo 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