0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラミングでエラーハンドリングといえばtry-catchが基本ですが、実はもう一つのブロックfinallyをご存知でしょうか?finallyは、エラーの有無に関わらず必ず実行される処理を記述するための便利な構文です。本記事では、try-catch-finallyの役割と使い方について解説します。

finallyとは?

finallyは、tryブロック内の処理が成功した場合でも、catchブロックでエラーが発生した場合でも、必ず実行される処理を記述するために使います。

try {
    // 実行したいコード
} catch (error) {
    // エラー時の処理
} finally {
    // 成功・失敗に関わらず実行される処理
}

使い道

用途としては、ファイルのリソース開放が一番イメージしやすいですね。

const readFile = () => {
    let fileHandle;
    try {
        fileHandle = openFile("example.txt");
        console.log(fileHandle.read());
    } catch (error) {
        console.error("Error reading file:", error);
    } finally {
        if (fileHandle) {
            fileHandle.close();
            console.log("File closed.");
        }
    }
};

try-catchどちらの場合も実行したい処理を書く場合、両方のブロックに書くなんてアホなことする人はいないと思いますが(多分過去の自分は書いたけど)、finallyを使わないと以下のようになります。シンプルにtry-catchの外に書けばいいだけですね。

const readFile = () => {
    let fileHandle;
    try {
        fileHandle = openFile("example.txt");
        console.log(fileHandle.read());
    } catch (error) {
        console.error("Error reading file:", error);
    }
    // finallyの代替コード
    if (fileHandle) {
        fileHandle.close();
        console.log("File closed.");
    }
};

じゃあ一つ目と二つ目が一緒ならfinallyがある意味ないんじゃない。。??(しいて言えば可読性が上がる??)と思いましたが、以下の記事を発見。これ以上ないほど分かりやすい説明だったので丸投げ紹介します。

余談ですが、finallyを知ったきっかけがCopilotが提案したコードに出てきたからです。独学者にとって「AIコード生成→動作確認→コードの意味調べ」という流れもありかもですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?