教學-46 異常

曾英-C#教學-46 異常編程

目錄

  • 瞭解什麼是異常
  • 掌握異常的編程的三種結構
    • 捕獲異常--try-catch結構
    • 收尾工做--try-catch-finally結構
    • 拋出異常--throw語句

1\異常概述

image

  • 能夠避免程序崩潰

1.1\異常的捕獲--try-catch結構

  • catch能夠只有一個/多個
  • 分母爲零程序崩潰只針對於整形,實型是不會報錯的
class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Console.WriteLine("請輸入分母:");
                int denominator = Convert.ToInt32(Console.ReadLine());
                double result = 100 / denominator;
                Console.WriteLine("結果:100/{0}={1}", denominator, result);
            }
            //這裏的異常名都是系統自帶的
            catch (DivideByZeroException)
            { Console.WriteLine("分母不能爲零"); }
            catch (FormatException)
            { Console.WriteLine("格式錯誤!"); }
        }
    }
}

  

1.2\收尾工做--try-catch-finally結構

  • finally:老是執行的,起到收尾的做用.
class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Console.WriteLine("請輸入分母:");
                int denominator = Convert.ToInt32(Console.ReadLine());
                double result = 100 / denominator;
                Console.WriteLine("結果:100/{0}={1}", denominator, result);
            }
            //這裏的異常名都是系統自帶的
            catch (DivideByZeroException)
            { Console.WriteLine("分母不能爲零"); }
            catch (FormatException)
            { Console.WriteLine("格式錯誤!"); }
            finally
            { Console.WriteLine("這是finally塊"); }
        }
    }

  

1.3\拋出異常--throw語句

class Program
    {
        
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("請輸入一個0-10之間的整數:");
                int number = Convert.ToInt32(Console.ReadLine());
                if (number < 0 || number > 10)
                { throw new IndexOutOfRangeException(); }//這個和catch中的關鍵字是同樣的
                else
                { Console.WriteLine("你輸入的整數是:{0}", number); }
            }
            catch (IndexOutOfRangeException)
            { Console.WriteLine("超出範圍"); }
            finally{Console.WriteLine("謝謝");}
        }

    }
相關文章
相關標籤/搜索