原来···是不是高手,看try cathch都能看出来···

本文通过具体代码示例,展示了如何在不同层级中合理使用异常抛出方法。主要对比了直接抛出异常与创建新异常的区别,并提供了实用建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一段代码:
View Code
 1     internal class ThrowAndThrowEx
2 {
3 public static void Test ()
4 {
5 Class1.DoSomething();
6 }
7 }
8
9
10 public class Class1
11 {
12 public static void DoSomething ()
13 {
14 try
15 {
16 Class2.DoSomething();
17 }
18 catch (Exception ex)
19 {
20 //throw;
21 throw new Exception("class1 call class2", ex);
22
23 }
24 }
25 }
26
27
28 public class Class2
29 {
30 public static void DoSomething ()
31 {
32 try
33 {
34 Class3.DoThrowOrThrowEx();
35 }
36 catch (Exception ex)
37 {
38 throw;
39 //throw ex;
40 }
41 }
42
43
44 }
45
46
47 public class Class3
48 {
49 public static void DoThrowOrThrowEx ()
50 {
51 try
52 {
53 int divider = 0;
54 int number = 5 / divider;
55 }
56 catch (Exception ex)
57 {
58 throw ex;
59 //throw;
60 }
61 }
62
63 }

 

 

如此来看 

 

可以在一些关键的分层次的地方使用:

                throw new Exception("class1 call class2", ex);

其他地方使用:

                throw;



 

转载于:https://www.cnblogs.com/scottgu/archive/2011/11/10/2244498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值