try-catch的使用(簡單用法 )

c#中異常捕獲c#

語法:spa

 

try數學

{string

有可能出現錯誤的代碼寫在這裏it

}語法

catch程序

{異常

出錯後的處理英語

}co

 

若是try中的代碼沒有出錯,則程序正常運行try中的內容後,不會執行catch中的內容,

若是try中的代碼一但出錯,程序當即跳入catch中去執行代碼,那麼try中出錯代碼後的全部代碼就再也不執行了.

 


 

例1:

try

{

Console.WriteLine("請輸入你的語文成績");

int chineseScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("請輸入你的數學成績");

int mathScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("你的總成績是:{0}\n你的平均成績是:{1}",chineseScore+mathScore,(chineseScore+mathScore)/2);

}

catch

{

Console.WriteLine("你輸入的有誤,請再次運行後輸入");

}

 

Console.ReadKey();

 


 

 

例2:

try

{

Console.WriteLine("請輸入你的姓名");

string name=Console.ReadLine();

Console.WriteLine("請輸入語文成績");

int chineseScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("請輸入數學成績");

int mathScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("請輸入英語成績");

int englishScore=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("{0}你的總分爲{1}分,平均爲{2}分",name,chineseScore+mathScore+englishScore,(chineseScore+mathScore+englishScore)/3);

}

catch

{

Console.WriteLine("你輸入的有誤,請從新運行本程序");

}

 

Console.ReadKey();


 

例3.1,

try

{

Console.WriteLine("請輸入你要計算的天數");

int days=Convert.ToInt32(Console.ReadLine()); 

int week=days/7;

int number=days%7; 

Console.WriteLine("{0}是{1},零{2}",days,week,number);

}

catch

{

Console.WriteLine("你輸入有誤,請從新啓動程序再輸一次");

}

Console.ReadKey();

 

例3.2:

 

try

{

Console.WriteLine("請輸入你要計算的天數");

int days=Convert.ToInt32(Console.ReadLine());

int month=days/30;

int week=(days-month*30)/7;

int dayNumber=days-month*30-week*7;

Console.WriteLine("{0}天中有{1}月,{2}周,{3}天.",days,month,week,dayNumber);

}

catch

{

 

Console.WriteLine("你輸入的有誤,請從新輸入一次");

}

Console.ReadKey();

上題也能夠這樣書寫代碼:

try

{

Console.WriteLine("請輸入你要計算的天數");

int days=Convert.ToInt32(Console.ReadLine());

int month=days/30;

int mot=days%30;//除去上面一個月30天的天數後還剩多少天.

int week=mot/7;//看看剩下的天數中有多少個周。

int dayNumber=mot%7;//除去上面一個周7天的天數後還剩多少天.

Console.WriteLine("{0}天中有{1}月,{2}周,{3}天",days,month,week,dayNumber);

}

catch

{

Console.WriteLine("你輸入的有誤,請從新輸入");

}

Console.ReadKey();

 

例3.3

try

{

Console.WriteLine("請輸入你要轉換的秒數");

int seconds=Convert.ToInt32(Console.ReadLine());

int days=seconds/(3600*24);//總秒數除以1天的秒數就得出有多少天數了

int mod=seconds%(3600*24);//看看除去上面秒數還剩下多少秒

int hours=mod/3600;//用上面一步剩下的秒除以1小時的秒數就得出有多少小時了

mod=mod%3600;//看看除去上面一步秒數還剩下多少秒

int min=mod/60;//用上面一步剩下的秒數除以1分鐘的秒數就得出有多少分鐘了

int second=mod%60;看看除去上面一步秒數還剩下多少秒

Console.WriteLine("{0}中共有{1}天,{2}小時,{3}分,{4}秒",seconds,days,hour,min,second);

}

catch

{

Console.WriteLine("你輸入有誤,請從新輸入");

}

Console.ReadKey();

相關文章
相關標籤/搜索