- 所有异常类型都派生于Exception类。
- 利用关键字try检测可能出现异常的语句块,利用关键字throw抛出异常对象,利用关键字catch执行捕捉到相应异常时的语句块。
- 若存在多个catch块,则程序会依次寻找与检测到的异常最匹配的catch块,因此捕捉Exception异常的catch块通常是最后一个catch块。
- 利用关键字finally执行无论前面是否捕捉到异常都会执行的语句块。
using System;
namespace _07
{
class Program
{
static void Main(string[] args)
{
Test.CatchException(new ArgumentException());
Console.WriteLine();
Test.CatchException(new TestException());
Console.WriteLine();
Test.CatchException(new Exception());
Console.WriteLine();
}
}
class Test
{
public static void CatchException(Exception exception)
{
try
{
throw exception;
}
catch (ArgumentException)
{
Console.WriteLine(new ArgumentException().Message);
}
catch (TestException)
{
Console.WriteLine(new TestException().Message);
}
catch (Exception)
{
Console.WriteLine(new Exception().Message);
}
finally
{
Console.WriteLine("Finally");
}
}
}
class TestException : Exception
{
public override string Message => "TestException";
}
}
