try catch里能否内嵌try catch?答案是肯定的。但是等内层try catch出异常之后是个什么执行顺序呢?看下面代码
static void Main(string[] args) { try { Console.WriteLine("----------------------外层try------------------------------"); errorMethod(); } catch (Exception ex) { Console.WriteLine("----------------------外层catch" + ex.Message + "------------------------------"); } finally { Console.WriteLine("----------------------外层finally------------------------------"); } Console.ReadKey(); } private static void errorMethod() { try { Console.WriteLine("----------------------内层try------------------------------"); int i = 0; int a = 100/i; } catch (Exception ex) { Console.WriteLine("----------------------内层catch" + ex.Message + "------------------------------"); } finally { Console.WriteLine("----------------------内层finally------------------------------"); } }
内层catch处理了异常,所以没有执行外层catch。
咱们把内层的catch注释掉 再试下
static void Main(string[] args) { try { Console.WriteLine("----------------------外层try------------------------------"); errorMethod(); } catch (Exception ex) { Console.WriteLine("----------------------外层catch" + ex.Message + "------------------------------"); } finally { Console.WriteLine("----------------------外层finally------------------------------"); } Console.ReadKey(); } private static void errorMethod() { try { Console.WriteLine("----------------------内层try------------------------------"); int i = 0; int a = 100/i; } //catch (Exception ex) //{ // Console.WriteLine("----------------------内层catch" + ex.Message + "------------------------------"); //} finally { Console.WriteLine("----------------------内层finally------------------------------"); } }
很明显,外层catch捕获了异常。
总结:try catch嵌套,内层不能捕获时,会考虑外层内否捕获,内层能捕获,则外层catch不执行。
try { //A try { //B } catch { //C } finally { //D } //E } catch { //F } finally { //G }
上面的代码 执行顺序
抛出异常在:内层A,E处由外层catch块捕获,并执行外层finally
抛出异常在:内层B处,且有一合适内层catch捕获,执行内层finally,后执行E处
抛出异常在:内层B处,但内层catch块没有合适处理程序,执行内层finally,搜索外层catch,找合适的,执行外层finally,此时不会执行E
抛出异常在:内层C处,退出内层catch块,执行内层finally,搜索外层catch,找到合适,执行外层finally
抛出异常在:内层D处,退出内层finally块,搜索外层catch,找到合适,执行外层finally
A抛异常 A=》F=》G
B抛异常 C能捕获 B=》C=》D=》E=》F=》G (若C处无法捕获B=》F=》G)
C抛异常 C=》D=》F=》G
D抛异常 D=》F=》G
E抛异常 A=》F=》G 同A
另外 try{}catch{} 中未做捕获类型限定,可捕获所以异常。如 try{}catch(IOException ex){} 则catch只能捕获I/O操作引发的异常。