天天看點

√ C# - 怎麼捕捉異常

1、所有的異常類型都派生于Exception類型。

2、利用關鍵字try檢測可能出現異常的語句塊,利用關鍵字throw抛出異常對象,利用關鍵字catch執行捕捉到相應異常時的語句塊。

3、若存在多個catch塊,則程式會依次尋找與檢測到的異常最比對的catch塊,是以捕捉Exception異常的catch塊通常是最後一個catch塊。

4、利用關鍵字finally執行無論前面是否捕捉到異常都會執行的語句塊。

using System;

namespace TryCatchException
{
    class Program
    {
        static void Main(string[] args)
        {
            Test.CatchException(new ArgumentException());
            Test.CatchException(new TestException());
            Test.CatchException(new Exception());
        }
    }

    public class Test
    {
        public static void CatchException<T>(T exception)
        {
            try
            {
                throw exception as 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\n");
            }
        }
    }

    public class TestException : Exception
    {
        public override string Message => "TestException";
    }
}
           
√ C# - 怎麼捕捉異常
c#