try catch嵌套以後出現異常執行順序:spa
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------------------------------"); } }
輸出結果:code
內層catch處理了異常,因此沒有執行外層catch,把內層的catch註釋掉,再試下:blog
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------------------------------"); } }
輸出結果:string
總結:try catch嵌套,內層不能捕獲時,會考慮外層內否捕獲,內層能捕獲,則外層catch不執行。it