C#测试代码:
using System; class Program { static void A() { try { Console.WriteLine("Throwing an exception"); throw new Exception("Did you catch it?"); } finally { Console.WriteLine("A.finally()"); } } static void B() { try { C(); Console.WriteLine("Failure! Exception has not been thrown."); } catch (Exception ex) { Console.WriteLine("Test B: success! Caught exception!\n" + ex.ToString()); } finally { Console.WriteLine("B.finally()"); } } static void C() { A(); } static void D() { try { try { Console.WriteLine("Throwing an exception"); throw new Exception("Did you catch it in the right handler?"); } catch (IndexOutOfRangeException e) { Console.WriteLine("Test D: Failed. Called wrong handler.\n" + e.ToString()); } } catch (Exception ex) { Console.WriteLine("Test D: success! Caught exception!\n" + ex.ToString()); } } static void Main() { Console.WriteLine("Testing A"); try { A(); Console.WriteLine("Failure! Exception has not been thrown."); } catch (Exception ex) { Console.WriteLine("Test A: success! Caught exception!\n" + ex.ToString()); } finally { Console.WriteLine("Main.finally()."); } Console.WriteLine("\nTesting B"); B(); Console.WriteLine("\nTesting D"); D(); Console.WriteLine("\nTesting class TestE"); TestE.Run(); Console.WriteLine("Exiting test"); } class TestE { static void A() { try { Console.WriteLine("In A"); B(); } catch (ArgumentException ae) { Console.WriteLine("Error! Caught ArgumentException.\n" + ae.ToString()); } } static void B() { try { Console.WriteLine("In B"); C(); } finally { Console.WriteLine("Leaving B"); } } static void C() { Console.WriteLine("In C"); D(); Console.WriteLine("Error! A() should not be reached in C()"); A(); } static void D() { Console.WriteLine("In D, throwing..."); throw new Exception("Exception test"); } public static void Run() { try { A(); } catch (Exception ex) { Console.WriteLine("Test C: success! Caught exception!\n" + ex.ToString()); } } } }