假设我们有一个公用方法叫openDB(),而很多方法中调用它,当数据库打开失败的时候,对于调用GetAllCount方法,异常将定位于 conn.Open而如果调用GetAllCount2,那么异常定位于throw sex的位置,同时堆栈信息也有所不同,可以更快捷的找到调用方法的位置,也可在此位置进行一些错误恢复处理。尤其是我们编写一些底层类库的时候,比如 Framework类库从不会把异常代码定位到Framework类库内部的某个方法上面。但是需要注意的是我们尽量避免捕获异常而不返回,例如 catch(){}
网管论坛bbs_bitsCN_com
这样的使用就是典型的错误使用了,因为对于Framework来讲,任何时候系统都可能抛出一个StackOverflowException或者OutOfMemoryExcetpion而上面这段代码则隐藏了这些异常,有时候则导致一些严重的问题。
中国网管论坛bbs.bitsCN.com
对于异常处理,在性能上有2点注意
网管下载dl.bitscn.com
第一点,在使用try/catch时,如果不发生异常,那么几乎可以忽略性能的损失。
中国网管联盟bitsCN.com
关于这一点,这里我们进行一些深入分析,对此比较了解的可以跳过本节。首先,让我们先看一下try/catch的IL表现。我们有2个方法,一个使用try/catch,而另一个未做任何处理: 网管bitscn_com
static int Test1(int a, int b) { try { if (a > b) return a; return b; } catch { return -1; } } static int Test2(int a, int b) { if (a > b) return a; return b; } 网管bitscn_com
|
网管u家u.bitsCN.com
使用ILDasm工具查看,IL代码分别如下:(这里之所以引入IL,是因为IL是比较接近机器汇编,所以在IL中我们可以更清楚的了解代码的执行情况,对IL没有兴趣的可以跳过此节)
网管论坛bbs_bitsCN_com
.method private hidebysig static int32 Test1(int32 a, int32 b) cil managed { // 代码大小 30 (0x1e) .maxstack 2 .locals init ([0] int32 CS$1$0000, [1] bool CS$4$0001) IL_0000: nop .try { IL_0001: nop IL_0002: ldarg.0 IL_0003: ldarg.1 IL_0004: cgt IL_0006: ldc.i4.0 IL_0007: ceq IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: brtrue.s IL_0011 IL_000d: ldarg.0 IL_000e: stloc.0 IL_000f: leave.s IL_001b IL_0011: ldarg.1 IL_0012: stloc.0 IL_0013: leave.s IL_001b 中国网管论坛bbs.bitsCN.com } // end .try catch [mscorlib]System.Object { IL_0015: pop IL_0016: nop IL_0017: ldc.i4.m1 IL_0018: stloc.0 IL_0019: leave.s IL_001b } // end handler IL_001b: nop IL_001c: ldloc.0 IL_001d: ret } // end of method Program::Test1 Test2 .method private hidebysig static int32 Test2(int32 a, int32 b) cil managed { // 代码大小 22 (0x16) .maxstack 2 .locals init ([0] int32 CS$1$0000, [1] bool CS$4$0001) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: cgt IL_0005: ldc.i4.0 IL_0006: ceq IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: brtrue.s IL_0010 IL_000c: ldarg.0 IL_000d: stloc.0 网管联盟bitsCN@com IL_000e: br.s IL_0014 IL_0010: ldarg.1 IL_0011: stloc.0 IL_0012: br.s IL_0014 IL_0014: ldloc.0 IL_0015: ret } // end of method Program::Test2 中国网管论坛bbs.bitsCN.com
|
网管联盟bitsCN_com
中国网管论坛bbs.bitsCN.com