1、输出调试信息:可以使用函数Debug.WriteLine();Trace.WriteLine();区别,在于前者只有在调试状态下才输出,后者还可以用于发布版本。2、try...catch...finally通过这个函数来捕获异常。3、附加代码在vs2010中亲自测试通过using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication9 { class Program { static string[] eTypes = { "none", "simple", "index", "nested index" }; //定义异常类型数组并存入string类型的数组中 static void Main(string[] args) { foreach (string eType in eTypes) //循环遍历异常类型 { try { Console.WriteLine("Main() try block reached."); Console.WriteLine("ThrowException("{0}") called.", eType); ThrowException(eType); Console.WriteLine("Main() try block continues."); } catch (System.IndexOutOfRangeException e) //索引超出范围异常 { Console.WriteLine("Main() System.IndexOutOfRangeException catch" + "block reached.Message:
"{0}"", e.Message); } catch { Console.WriteLine("Main() general catch block reached."); //普通catch捕获 } finally //有无异常都始终会输出 { Console.WriteLine("Main() finally block reached."); } Console.WriteLine(); } Console.ReadKey(); } static void ThrowException(string exceptionType) { Console.WriteLine("ThrowException("{0}") reached ." ,exceptionType ); switch (exceptionType) { case "none": //不抛出异常 Console.WriteLine("Not throwing an exception."); break; case "simple": //生成一般异常 Console.WriteLine("Throwing System.Exception."); throw (new System.Exception()); break; case "index": //生成System.IndexOutOfRangeException.异常 Console.WriteLine("Throwing System.IndexOutOfRangeException."); eTypes[4] = "error"; break; case "nested index": //包含自己的try块,其中调用index情况 try { Console.WriteLine("ThrowException("nested index")" + "try block reached."); Console.WriteLine("ThrowException ("index") called."); ThrowException("index"); } catch { Console.WriteLine("throwException("nested index") general" + "catch block reached."); } finally { Console.WriteLine("ThrowExceptiopn("nested index") finally" + " block reached."); } break; } } } }
收藏该网址