如何:捕捉异常 (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# 速成版