在上一節(jié)中,我們已經(jīng)看到了如何處理CLR自動(dòng)引發(fā)的異常。在這里,我們將看到如何手動(dòng)引發(fā)異常。
可以使用throw關(guān)鍵字手動(dòng)引發(fā)異常??梢允褂胻hrow關(guān)鍵字引發(fā)從Exception類派生的任何類型的異常。
static void Main(string[] args)
{
Student std = null;
try
{
PrintStudentName(std);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
}
Console.ReadKey();
}
private static void PrintStudentName( Student std)
{
if (std == null)
throw new NullReferenceException("Student 對(duì)象為null");
Console.WriteLine(std.StudentName);
}Student 對(duì)象為null
在上面的示例中,如果Student對(duì)象為null ,則 PrintStudentName()方法拋出 NullReferenceException。
請(qǐng)注意,throw使用new關(guān)鍵字創(chuàng)建了任何有效異常類型的對(duì)象。throw關(guān)鍵字不能與不是從Exception類派生的任何其他類型一起使用。
您還可以從catch塊中重新引發(fā)異常,以將其傳遞給調(diào)用方,并讓調(diào)用方以所需的方式對(duì)其進(jìn)行處理。下面的示例重新引發(fā)異常。
static void Main(string[] args)
{
try
{
Method1();
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
static void Method1()
{
try
{
Method2();
}
catch(Exception ex)
{
throw;
}
}
static void Method2()
{
string str = null;
try
{
Console.WriteLine(str[0]);
}
catch(Exception ex)
{
throw;
}
}在上面的示例中,Method2()中發(fā)生異常。catch塊僅使用throw關(guān)鍵字(而不是throw e)僅引發(fā)該異常。這將在Method1()的catch塊中處理,在此它再次重新引發(fā)相同的異常,最后在該Main()方法中對(duì)其進(jìn)行處理。此異常的堆棧跟蹤將為您提供確切位置確切說明此異常的完整詳細(xì)信息。
如果使用異常參數(shù)重新拋出異常,則它將不會(huì)保留原始異常并創(chuàng)建新的異常。以下示例對(duì)此進(jìn)行了演示。
static void Main(string[] args)
{
try
{
Method1();
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
static void Method1()
{
try
{
Method2();
}
catch(Exception ex)
{
throw ex;
}
}
static void Method2()
{
string str = null;
try
{
Console.WriteLine(str[0]);
}
catch(Exception ex)
{
throw;
}
}在上面的示例中,Main ()方法中捕獲的異常將顯示來自 Method1和 Main 方法的堆棧跟蹤。當(dāng)我們?cè)?Method1()中使用 throw ex 重新拋出異常時(shí),它將不會(huì)在堆棧跟蹤中顯示 Method1。因此,千萬不要使用 throw < exception parameter parameter > 來拋出異常。
在下一節(jié)中了解如何創(chuàng)建自定義異常類型。