簡體   English   中英

如果在“try-catch”塊內發生錯誤,如何返回,並且仍然在 finally 中運行代碼?

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

如果try塊內發生錯誤,我正在嘗試退出 function,並且仍然在finally中運行清理代碼。

我通過使用最初設置為trueshouldContinue來做到這一點,如果不應該繼續執行,則在 catch 塊內將其設置為false

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

}

try塊內發生錯誤並仍然在finally中運行代碼后,有沒有更好的方法來退出 function ?

一種方法(可能是我個人首選的方法)是簡單地將所有內容放在 try 中(如果可能的話 - 例如,如果 try 中沒有其他內容可能引發不相關的錯誤):

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();
    }

}

另一種方法是在 catch 中返回(最終仍然運行):

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

}

finally 無論如何都會被執行,無論是 try 執行還是 catch。

我很困惑,既然您想在發生錯誤時清理 session,為什么不將清理代碼放在 catch 塊中?因為它在 try 塊發生錯誤時執行。 為什么你必須使用finally? 如果你使用 finally 它將在最后清理 session 是否有錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM