C# - throw 关键字
我们已经在上一节中了解了如何处理由 CLR 自动引发的异常。在这里,我们将学习如何手动引发异常。
可以使用 throw 关键字手动引发异常。任何派生自 Exception 类的异常类型都可以使用 throw 关键字引发。
示例:抛出异常
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 object is null.");
Console.WriteLine(std.StudentName);
}
输出
学生对象为空。在上面的示例中,如果 Student 对象为空,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 块中处理,Method1() 再次重新抛出相同的异常,最后它在 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,因为我们在 Method1() 中使用 throw ex
重新抛出异常。因此,切勿使用 throw <exception parameter>
抛出异常。
在下一节中学习如何创建自定义异常类型。