Try ブロックと Catch ブロックを使用して例外をキャッチする方法

例外を発生またはスローする可能性のあるコード ステートメントはいずれも try ブロックに配置し、1 つまたは複数の例外を処理するのに使用されるステートメントは try ブロックの下にある 1 つまたは複数の catch ブロックに配置します。 各 catch ブロックには例外の種類が含まれており、その例外の種類を処理するのに必要なステートメントを追加で含めることができます。

次の例では、StreamReader を使用して、data.txt と呼ばれるファイルを開き、そのファイルから行を取得します。 コードからは 3 つの例外のいずれかがスローされる可能性があります。そのため、コードは try ブロックに配置します。 3 つの catch ブロックでは例外がキャッチされます。さらに結果をコンソールに表示してそれらの例外が処理されます。

using namespace System;
using namespace System::IO;

public ref class ProcessFile
{
public:
    static void Main()
    {
        try
        {
            StreamReader^ sr = File::OpenText("data.txt");
            Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
            sr->Close();
        }
        catch (Exception^ e)
        {
            Console::WriteLine("An error occurred: '{0}'", e);
        }
    }
};

int main()
{
    ProcessFile::Main();
}
using System;
using System.IO;

public class ProcessFile
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = File.OpenText("data.txt"))
            {
                Console.WriteLine($"The first line of this file is {sr.ReadLine()}");
            }
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"The file was not found: '{e}'");
        }
        catch (DirectoryNotFoundException e)
        {
            Console.WriteLine($"The directory was not found: '{e}'");
        }
        catch (IOException e)
        {
            Console.WriteLine($"The file could not be opened: '{e}'");
        }
    }
}
Imports System.IO

Public Class ProcessFile
    Public Shared Sub Main()
        Try
            Using sr As StreamReader = File.OpenText("data.txt")
                Console.WriteLine($"The first line of this file is {sr.ReadLine()}")
            End Using
        Catch e As FileNotFoundException
            Console.WriteLine($"The file was not found: '{e}'")
        Catch e As DirectoryNotFoundException
            Console.WriteLine($"The directory was not found: '{e}'")
        Catch e As IOException
            Console.WriteLine($"The file could not be opened: '{e}'")
        End Try
    End Sub
End Class

共通言語ランタイム (CLR) では、catch ブロックで処理されない例外がキャッチされます。 CLR によって例外がキャッチされると、ご利用の CLR 構成に応じて次の結果のいずれかが発生する場合があります。

  • [デバッグ] ダイアログ ボックスが表示されます。
  • プログラムの実行が停止され、例外情報を含むダイアログ ボックスが表示されます。
  • 標準エラー出力ストリームにエラーが出力されます。

注意

ほとんどのコードで例外がスローされる可能性があります。また、OutOfMemoryException のように、CLR 自体によっていつでもスローされる可能性のある例外もあります。 アプリケーションではこのようの例外を処理する必要はありませんが、他のユーザーが使用するライブラリを記述する際には、必要となる可能性があるので注意してください。 try ブロック内でコードを設定するタイミングに関しては、「例外の推奨事項」を参照してください。

関連項目