在上一节中,我们已经看到了如何处理CLR自动引发的异常。在这里,我们将看到如何手动引发异常。
可以使用throw关键字手动引发异常。可以使用throw关键字引发从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 对象为null");
Console.WriteLine(std.StudentName);
}Student 对象为null
在上面的示例中,如果Student对象为null ,则 PrintStudentName()方法抛出 NullReferenceException。
请注意,throw使用new关键字创建了任何有效异常类型的对象。throw关键字不能与不是从Exception类派生的任何其他类型一起使用。
您还可以从catch块中重新引发异常,以将其传递给调用方,并让调用方以所需的方式对其进行处理。下面的示例重新引发异常。
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()中发生异常。catch块仅使用throw关键字(而不是throw e)仅引发该异常。这将在Method1()的catch块中处理,在此它再次重新引发相同的异常,最后在该Main()方法中对其进行处理。此异常的堆栈跟踪将为您提供确切位置确切说明此异常的完整详细信息。
如果使用异常参数重新抛出异常,则它将不会保留原始异常并创建新的异常。以下示例对此进行了演示。
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 方法的堆栈跟踪。当我们在 Method1()中使用 throw ex 重新抛出异常时,它将不会在堆栈跟踪中显示 Method1。因此,千万不要使用 throw < exception parameter parameter > 来抛出异常。
在下一节中了解如何创建自定义异常类型。