1. 程式人生 > >使用try,catch,finally處理錯誤異常

使用try,catch,finally處理錯誤異常

先講一下處理異常的語法結構:
在這裡插入圖片描述

舉一個錯誤異常的例子:

 class Program
    {
     
        static void Main(string[] args)
        {
            try
            {
                int[] myArray = {1, 2, 3, 4};
                int myEle = myArray[4];
            }

從上面程式碼可以看出,myArray[4]陣列下標越界了
在這裡插入圖片描述
所以現在使用try,catch,finally來處理這個異常:

 class Program
    {
        
        static void Main(string[] args)
        {

            try
            {
                int[] myArray = { 1, 2, 3, 4 };
                int myEle = myArray[4];
            }

            catch (IndexOutOfRangeException e)//當捕捉的異常與程式碼發生的異常相同時,程式可繼續執行catch裡的程式碼,括號內放的是異常的物件
            {
                Console.WriteLine("異常,陣列下標越界");
            }
            finally
            {
                Console.WriteLine("這裡是finally");
            }
     }
   }

執行的結果為:
在這裡插入圖片描述
從結果可以看出,使用了異常處理的情況下,程式依然能執行,輸出了catch塊和finally塊的語句

我們再看下面的程式碼:

class Program
    {
        static void Main(string[] args)
        {

            try
            {
                int[] myArray = { 1, 2, 3, 4 };
                int myEle = myArray[4];
            }

            catch (NullReferenceException e)//當捕捉的異常與程式碼發生的異常不同時,程式會終止
            {
                Console.WriteLine("異常");
                Console.WriteLine("訪問陣列的時候越界了");
            }
              finally
            {
                Console.WriteLine("這裡是finally");
            }

            Console.ReadKey();
        }
    }

執行的結果為:
在這裡插入圖片描述
程式在異常處終止了,原因是在catch塊捕捉的異常與程式碼的異常不同,所以程式終止無法執行。

再看多一個例子:

class Program
    {
        static void Main(string[] args)
        {

            try
            {
                int[] myArray = { 1, 2, 3, 4 };
                int myEle = myArray[4];
            }
             catch//當沒有指定捕捉異常的內容時,能夠捕捉到所有異常,程式執行
            {
                Console.WriteLine("異常,陣列下標越界");
            }

            finally
            {
                Console.WriteLine("這裡是finally");
            }

            Console.ReadKey();
        }
    }

執行結果為:
在這裡插入圖片描述
與第一個例子一樣輸出了catch塊和finally塊的語句,唯一不同的是在程式碼裡catch塊沒有指定捕捉異常的內容

根據以上例子總結:
1.使用try,catch,finally語法處理異常可以使程式碼在異常的情況下繼續執行。
2.當catch塊指定捕捉的異常與程式碼異常不同時,程式會被終止。
3.當catch塊沒有指定捕捉異常內容時,任何異常都會被捕捉。
4.當代碼沒有異常時,catch塊的內容不會被執行。
4.只要程式能夠執行,finally塊的內容都會被執行。