C# try catch

來源:互聯網
上載者:User

標籤:程式   for   gen   實驗   定義   space   image   static   lin   

1、代碼放到try快中(try是c#的關鍵字)。代碼運行是,會嘗試執行try塊內部的語句,如果麼有語句發生異常,這些語句將順序執行下去。直到全部都完成,但是一旦出現異常就跳出try塊,執行catch塊中的內容。2、try塊需要一個或者多個catch塊程式捕捉並處理特定類型的異常。

  實驗步驟:首先通過控制台程式輸入一串字元,使用Console.readLine();擷取一串字串資料。

       然後使用後int.parse(string s);這個函數將字串轉換為int型資料。

       通過查看int.parse(string s);函數定義可以知道他又如下異常。

      

 // 異常:        //   T:System.ArgumentNullException:        //     s 為 null。        //        //   T:System.FormatException:        //     s 的格式不正確。        //        //   T:System.OverflowException:        //     s 表示一個小於 System.Int32.MinValue 或大於 System.Int32.MaxValue 的數字。

      實現代碼:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace tesetData{    class Program    {                      static void Main(string[] args)        {            //try catch的使用             string readString = Console.ReadLine();            int readValue;            try            {                readValue = int.Parse(readString);                Console.WriteLine(readValue);            }            catch (OverflowException)            {                Console.WriteLine("err:轉化的不是一個int型資料");            }            catch (FormatException)            {                Console.WriteLine("err:格式錯誤");            }            catch (ArgumentNullException)            {                Console.WriteLine("err:null");            }            Console.ReadLine();        }    }}

      

 

 

 

C# try catch

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.