Menu
Coddy logo textTech

Finally Block

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 27/66。

finally ブロックには、例外が発生したかどうかに関わらず、常に実行されるコードが含まれています。try または catch ブロックに return 文があった場合でもです。

基本的な try-catch-finally 構造を作成する:

try
{
    // Code that might throw an exception
    int result = 10 / 2;
    Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
    // Code that handles the exception
    Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
    // Code that always executes
    Console.WriteLine("This always executes");
}

finally ブロックは、ファイルやデータベース接続を閉じるなどのクリーンアップ作業に便利です:

System.IO.StreamReader file = null;
try
{
    file = new System.IO.StreamReader("data.txt");
    string content = file.ReadToEnd();
    Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
    Console.WriteLine("File not found.");
}
finally
{
    // 例外が発生した場合でも、常にファイルを閉じる
    if (file != null)
    {
        file.Close();
    }
}
challenge icon

チャレンジ

簡単

ProcessData という名前のメソッドを作成し、以下の機能を実装してください:

  1. ファイル名を表す文字列パラメータを受け取る
  2. ファイルを開いて内容を読み込もうとする
  3. 内容をコンソールに出力する
  4. finally ブロックを使用してリソースを適切にクリーンアップする
  5. FileNotFoundException と IOException を処理する

ファイルが見つからない場合、"ERROR: File not found: [filename]" と出力してください

別の IO エラーが発生した場合、"ERROR: Could not read the file: [error message]" と出力してください

例外が発生したか否かにかかわらず、finally ブロック内で常に "File operation completed." を出力してください。

チートシート

finally ブロックは、例外が発生したかどうかに関わらず、常に実行されるコードを含みます。try または catch ブロックに return 文があっても同様です。

基本的な try-catch-finally 構造:

try
{
    // Code that might throw an exception
    int result = 10 / 2;
    Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
    // Code that handles the exception
    Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
    // Code that always executes
    Console.WriteLine("This always executes");
}

finally ブロックは、ファイルやデータベース接続のクローズなどのクリーンアップタスクに便利です:

System.IO.StreamReader file = null;
try
{
    file = new System.IO.StreamReader("data.txt");
    string content = file.ReadToEnd();
    Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
    Console.WriteLine("File not found.");
}
finally
{
    // Always close the file, even if an exception occurred
    if (file != null)
    {
        file.Close();
    }
}

自分で試してみよう

using System;
using System.IO;

class Program
{
    public static void ProcessData(string filename)
    {
        // ここにコードを書いてください
    }
    
    static void Main(string[] args)
    {
        string filename = Console.ReadLine();
        ProcessData(filename);
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン