C# 程序员使用 try 块来对可能受异常影响的代码进行分区,并使用 catch 块来处理所产生的任何异常。不管是否引发异常,都可以使用 finally 块来执行代码 -- 有时必须这样做,因为如果引发异常,将不执行 try/catch 构造后面的代码。try 块必须与 catch 或 finally 块一起使用,并且可以包括多个 catch 块。例如:

C# CopyCode image复制代码
try
{
    // Code to try here.
}
catch (System.Exception ex)
{
    // Code to handle exception here.
}
C# CopyCode image复制代码
try
{
    // Code to try here.
}
finally
{
    // Code to execute after try here.
}
C# CopyCode image复制代码
try
{
    // Code to try here.
}
catch (System.Exception ex)
{
    // Code to handle exception here.
}
finally
{
    // Code to execute after try (and possibly catch) here.
}

没有 catchfinally 块的 try 语句将产生编译器错误。

Expand 图像Catch 块

Expand 图像Finally 块

Expand 图像C# 语言规范

Expand image请参见