MSDN: try-catch
try-catch 语句由一个 try 块和其后所跟的一个或多个 catch 子句(为不同的异常指定处理程序)构成。此语句会采用下列形式之一:
try try-block catch (exception-declaration-1) catch-block-1 catch (exception-declaration-2) catch-block-2 ... try try-block catch catch-block
其中:
- try-block
- 包含应引发异常的代码段。
- exception-declaration, exception-declaration-1, exception-declaration-2
- 异常对象声明。
- catch-block, catch-block-1, catch-block-2
-
包含异常处理程序。
示例
此例使用了两个 catch 语句。最先出现的最特定的异常被捕获。
// Ordering catch clauses
using System;
class MyClass
{
public static void Main()
{
MyClass x = new MyClass();
try
{
string s = null;
x.MyFn(s);
} - // Most specific:
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception caught.", e);
} - // Least specific:
catch (Exception e)
{
Console.WriteLine("{0} Second exception caught.", e);
} - }
- public void MyFn(string s)
{
if (s == null)
throw new ArgumentNullException();
}
}
输出
System.ArgumentNullException:Value cannot be null.
at ...
at... First exception caught.