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

181
Vistas
How to return if an error occurs inside a `try-catch` block, and still run code in finally?

I'm trying to exit the function if an error occurs inside the try block, and still run cleanup code in finally.

I'm doing it by using shouldContinue that is set to true initially, and set it to false inside the catch block if the execution shouldn't continue.

async uploadToServer() {
    let response;
    let shouldContinue = true;

    try {
        response = await this.uploderService.uploadFileToServer();

    } catch (error) {
        this.displayUploadError(error);
        shouldContinue = false;

    } finally {
        // run cleanup code anyway
        this.resetSession();
    }

    if (!shouldContinue) {
        return;
    }

    this.saveResponse(response);
    // continue execution here
    // ...

}

Is there a better way to exit the function after an error occurs inside the try block and still run code in finally?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

One way (probably my personal preferred way) is to simply put everything inside the try (if possible - e.g. if nothing else inside the try could throw an unrelated error):

async uploadToServer() {

    try {
        const response = await this.uploderService.uploadFileToServer();
        this.saveResponse(response);
        // continue execution here
        // ...
    } catch (error) {
        this.displayUploadError(error);
    } finally {
        // run cleanup code anyway
        this.resetSession();
    }

}

Another way is to return in the catch (finally still runs):

async uploadToServer() {
    let response;

    try {
        response = await this.uploderService.uploadFileToServer();
    } catch (error) {
        this.displayUploadError(error);
        return;
    } finally {
        // run cleanup code anyway
        this.resetSession();
    }

    this.saveResponse(response);
    // continue execution here
    // ...

}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Finally will be executed anyway, either the try executed or catch. Check the description in the link below for more information.
Mozilla developer reference

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