或者再深一層有拋出Exception但你沒有執行catch區塊, 那麼在compile階段就會報error
一個簡單的範例程式如下:
public class throwTest { private static void throwTestLayer1() throws Exception { System.out.println("throwTestLayer1: throw Exception +++"); throw new Exception("throwTestLayer1: throwExcept test"); } private static void throwTestLayer2() throws Exception { System.out.println("throwTestLayer2: calling throwTestLayer1 +++"); throwTestLayer1(); System.out.println("throwTestLayer2: calling throwTestLayer1 ---"); } private static void throwTestLayer2Catch() throws Exception { try { System.out.println("throwTestLayer2Catch: calling throwTestLayer1 +++"); throwTestLayer1(); System.out.println("throwTestLayer2Catch: calling throwTestLayer1 ---"); } catch (Exception e) { System.out.println("throwTestLayer2Catch: Catch throwTestLayer1"); e.printStackTrace(); //throw e; } } public static void main(String[] argv) {
// 單層的 throw System.out.println("============================================================="); try { System.out.println("main: Calling throwTestLayer1 +++"); throwTestLayer1(); System.out.println("main: Calling throwTestLayer1 ---"); } catch (Exception e) { System.out.println("main: Catch throwTestLayer1"); e.printStackTrace(); } System.out.println("=============================================================");
// 這個 throwTestLayer2 並沒有去執行 try/catch, 他必須宣告 throwsSystem.out.println("============================================================="); try { System.out.println("main: Calling throwTestLayer2 +++"); throwTestLayer2(); System.out.println("main: Calling throwTestLayer2 ---"); } catch (Exception e) { System.out.println("main: Catch throwTestLayer2"); e.printStackTrace(); } System.out.println("=============================================================");
// 這個 throwTestLayer2Catch 將會執行 catch, 如果它不再 throw, 這時候 main 是接不到的System.out.println("============================================================="); try { System.out.println("main: Calling throwTestLayer2Catch +++"); throwTestLayer2Catch(); System.out.println("main: Calling throwTestLayer2Catch ---"); } catch (Exception e) { System.out.println("main: Catch throwTestLayer2Catch"); e.printStackTrace(); } System.out.println("============================================================="); } }
沒有留言:
張貼留言