异常处理

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
包含异常处理程序。
备注
try-block 包含可能导致异常的保护代码块。该块一直执行到引发异常或成功完成为止。例如,下列转换 null 对象的尝试引发 NullReferenceException 异常:
object o2 = null;
try
{
   int i2 = (int) o2;   // Error
}
catch 子句使用时可以不带任何参数,在这种情况下它捕获任何类型的异常,并被称为一般 catch 子句。它还可以采用从 System.Exception 派生的对象参数,在这种情况下它处理特定的异常。例如:
catch (InvalidCastException e)
{
}
在同一个 try-catch 语句中可以使用一个以上的特定 catch 子句。这种情况下 catch 子句的顺序很重要,因为会按顺序检查 catch 子句。将先捕获特定程度较高的异常,而不是特定程度较小的异常。
在 catch 块中可以使用 throw 语句再次引发已由 catch 语句捕获的异常。例如:
catch (InvalidCastException e)
{
   throw (e);   // Rethrowing exception e
}
如果要再次引发当前由无参数的 catch 子句处理的异常,则使用不带参数的 throw 语句。例如:
catch
{
   throw;
}
请在 try 块内部只初始化其中声明的变量;否则,完成该块的执行前可能发生异常。例如,在下面的代码示例中,变量 x 在 try 块内初始化。试图在 Write(x) 语句中的 try 块外部使用此变量时将生成编译器错误:使用了未赋值的局部变量。
public static void Main()
{
   int x;
   try
   {
      x = 123;   //   Don't do that.
      // ...
   }
   catch
   {
      // ...
   }
   Console.Write(x);   // Error: Use of unassigned local variable 'x'.
}
有关 catch 的更多信息,请参见 try-catch-finally。
示例
在此例中,try 块包含对可能导致异常的 MyFn() 方法的调用。catch 子句包含仅在屏幕上显示消息的异常处理程序。当从 MyFn() 内部调用 throw 语句时,系统查找 catch 语句并显示 Exception caught 消息。
// Rethrowing exceptions:
using System;
class MyClass
{
   public static void Main()
   {
      MyClass x = new MyClass();
      try
      {
         string s = null;
         x.MyFn(s);
      }

      catch (Exception e)
      {
         Console.WriteLine("{0} Exception caught.", e);
      }
   }

   public void MyFn(string s)
   {
      if (s == null)
         throw(new ArgumentNullException());
   }  
}
输出
发生以下异常:
System.ArgumentNullException
示例
此例使用了两个 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
在前面的示例中,如果从特定程度最小的 catch 子句开始,您将收到此错误信息:
A previous catch clause already catches all exceptions of this or a super type ('System.Exception')
但是,若要捕获特定程度最小的异常,请使用下面的语句替换 throw 语句:
throw new Exception();

posted @ 2009-03-18 16:56  韩冰冰  阅读(207)  评论(0编辑  收藏  举报