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:\n\"{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;
}
}
}
}