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             }

 

posted @ 2018-09-24 18:17  邢韬  阅读(1177)  评论(0编辑  收藏  举报