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             }

 

转载于:https://www.cnblogs.com/xt112233/p/9696149.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值