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

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

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 Relatório

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 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