catch 块,则 CLR 会向用户显示一条有关未经处理的异常的消息并停止执行程序。
NullReferenceException 异常:
object o2 = null;
try
{
int i2 = (int)o2; // Error
}
System.Exception 派生的对象参数。例如:
catch (InvalidCastException e)
{
}
如果对 catch 块进行排序以使永远不能达到后面的块,编译器将产生错误。
IOException 异常中提取源信息,然后向父方法发送异常。
catch (FileNotFoundException e)
{
// FileNotFoundExceptions are handled here.
}
catch (IOException e)
{
// Extract some information from this exception, and then
// throw it to the parent method.
if (e.Source != null)
Console.WriteLine("IOException source: {0}", e.Source);
throw;
}
执行此操作时,指定将其作为内部异常捕获的异常,如下面的示例所示。
catch (InvalidCastException e)
{
// Perform some action here, and then throw a new exception.
throw new YourCustomException("Put your error message here.", e);
}
还可以在指定的条件为真是重新引发异常,如下面的示例所示。
catch (InvalidCastException e)
{
if (e.Data == null)
{
throw;
}
else
{
// Take some action.
}
}
try 块外部使用此变量,则会生成编译器错误。
static void Main()
{
int n;
try
{
// Do not initialize this variable here.
n = 123;
}
catch
{
}
// Error: Use of unassigned local variable 'n'.
Console.Write(n);
}
try-catch-finally。
Exception caught 消息。
class TryFinallyTest { static void ProcessString(string s) { if (s == null) { throw new ArgumentNullException(); } } static void Main() { string s = null; // For demonstration purposes. try { ProcessString(s); } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } } } /* Output: System.ArgumentNullException: Value cannot be null. at TryFinallyTest.Main() Exception caught. * */
最先出现的最特定的异常被捕获。
class ThrowTest3 { static void ProcessString(string s) { if (s == null) { throw new ArgumentNullException(); } } static void Main() { try { string s = null; ProcessString(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); } } } /* Output: System.ArgumentNullException: Value cannot be null. at Test.ThrowTest3.ProcessString(String s) ... First exception caught. */
在前面的示例中,如果从具体程度最低的 catch 子句开始,您将收到以下错误信息:
A previous catch clause already catches all exceptions of this or a super type ('System.Exception')
但是,若要捕获特定程度最小的异常,请使用下面的语句替换 throw 语句:
throw new Exception();