c# 異常處理


嵌套

異常嵌套可一起檢查多個異常,其中一環出現異常,便停止排查余下異常

 1   public class TryCatch
 2     {
 3         public void Test1(int a )
 4         {
 5             try
 6             {
 7                 int i = 1 / a;
 8 
 9                 Console.WriteLine(i);
10                 try
11                 {
12                     int j = i + 1;        //異常嵌套
13                     Console.WriteLine(j);
14                 }
15                 catch (IndexOutOfRangeException e)
16                 {
17                     Console.WriteLine(e.Message);
18                     Console.WriteLine(e.StackTrace);
19 
20 
21                 }
22             }
23             catch(Exception e )   //當不知道異常種類時用Exception
24             {
25                 Console.WriteLine(e.Message);
26             }
27             finally
28             {
29                 Console.WriteLine("結果");
30             }
31 
32         }
33     }

多重異常處理

Argument三個異常為參數相關,需先定義一下

 1     public class Exceptions
 2     {
 3         public static void Text1(string name,int age,string sex)
 4         {
 5             if (string .IsNullOrWhiteSpace(name))
 6             {
 7                 throw new ArgumentNullException("name"); 
 8             }
 9             if (sex!="boy" &&sex!= "girl")
10             {
11                 throw new ArgumentException("sex");
12             }
13             if (age>=150 || age <=0)
14             {
15                 throw new ArgumentOutOfRangeException("age");
16             }
17             Console.WriteLine(name + age + sex);
18         }
19 }
定義參數異常
 1   
 2             try
 3             {
 4                 Exceptions.Text1("tt", 23, "boy");
 5                 Console.WriteLine("無異常");
 6             }
 7 
 8             catch (ArgumentNullException e)
 9             {
10                 Console.WriteLine(e.Message);
11                 Console.WriteLine(e.StackTrace);
12             }
13             catch (ArgumentOutOfRangeException e)
14             {
15                 Console.WriteLine(e.Message);
16                 Console.WriteLine(e.StackTrace);
17             }
18             catch (ArgumentException e)
19             {
20                 Console.WriteLine(e.Message);
21                 Console.WriteLine(e.StackTrace);
22             }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM