Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!