第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

C# - 如何使用 try-catch 塊處理此代碼中的錯(cuò)誤?

C# - 如何使用 try-catch 塊處理此代碼中的錯(cuò)誤?

C#
繁華開滿天機(jī) 2022-06-18 17:28:49
我有這個(gè)代碼:else if (number == 5)        {            Console.Write("Student's index: ");            int index1 = int.Parse(Console.ReadLine());            try            {                customDataList.FindStudent(index1); //displays the element that has the specified index            }            catch (ArgumentOutOfRangeException)            {                Console.WriteLine("Please choose an index from 0 to 9!");            }        }當(dāng)用戶未輸入任何字符或輸入非整數(shù)字符時(shí),我需要使用 try-catch 處理錯(cuò)誤。怎么可能呢?
查看完整描述

2 回答

?
HUWWW

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊

用于TryParse檢查輸入是否為整數(shù)。然后,如果它是一個(gè)整數(shù),對索引做任何你想做的事情。


else if (number == 5)

{

    Console.Write("Student's index: ");

    var success = int.TryParse(Console.ReadLine(), out int index1);

    if (success)

    {

        //next logic here if the input is an integer

        try

        {

            customDataList.FindStudent(index1); //displays the element that has the specified index

        }

        catch (ArgumentOutOfRangeException)

        {

            Console.WriteLine("Please choose an index from 0 to 9!");

        }

    }

    else

    {

        //do something when the input is not an integer

    }

}


查看完整回答
反對 回復(fù) 2022-06-18
?
翻閱古今

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊

您需要int.Parse在 try {} 塊內(nèi)移動(dòng)您的行。只有這樣,它才會(huì)在結(jié)構(gòu)化異常處理的安全網(wǎng)中。然后,您可以針對 FormatException 添加第二個(gè) catch {} 塊,請參閱 Int32.Parse 文檔以了解引發(fā)的異常。


else if (number == 5)

{

    Console.Write("Student's index: ");


    try

    {

        int index1 = int.Parse(Console.ReadLine());

        customDataList.FindStudent(index1); //displays the element that has the specified index

    }

    catch (ArgumentOutOfRangeException)

    {

        Console.WriteLine("Please choose an index from 0 to 9!");

    }

    catch (FormatException)

    {

        Console.WriteLine("Error: Index must be a number.");

    }

}


查看完整回答
反對 回復(fù) 2022-06-18
  • 2 回答
  • 0 關(guān)注
  • 137 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號