Share via


方法 : 例外をキャッチする (Visual C#)

更新 : 2007 年 11 月

try-catch ブロックを使用して、ゼロによる除算を例外としてキャッチする例を次に示します。例外がキャッチされた後、実行は finally ブロックで再開されます。

使用例

int top = 0, bottom = 0, result = 0;

try
{
    result = top / bottom;
}
catch (System.Exception ex)
{
    System.Console.WriteLine("{0} exception caught here.", ex.GetType().ToString());
    System.Console.WriteLine(ex.Message);
}
finally
{
    System.Console.WriteLine("Clean-up code executes here...");
}
System.Console.WriteLine("Program execution continues here...");
System.DivideByZeroException exception caught here.
Attempted to divide by zero.
Clean-up code executes here...
Program execution continues here...

コードのコンパイル方法

コードをコピーし、コンソール アプリケーションの Main メソッドに貼り付けます。

参照

その他の技術情報

Visual C# Express