Exceptionの復習
まず親クラスを作って、子クラスでExceptionを投げたりcatchしたりしてみる。
public class Parent { public static void main(String[]args){ try{ Children child = new Children(); child.throwExceptionTry(); } catch (Exception e) { System.out.println("ここまでおいで"); } finally { System.out.println("お疲れ様でした。"); } System.out.println("終わったのかしら。"); } }
まず、子クラスでExceptionの処理を行なうパターン
public void throwExceptionTry(){ try { throw new Exception(); } catch (Exception e) { System.out.println("try~catchしました。"); System.out.println("/n"); } }
結果
try~catchしました。
/n
お疲れ様でした。
終わったのかしら。
もちろん、親クラスでtry〜chcheしていない場合は、エラーになります。
次に、子クラスでは処理を行わずにExceptionを返してくるクラスを呼ぶ場合。
public void throwExceptionThrows() throws Exception{ throw new Exception(); }
結果
ここまでおいで
お疲れ様でした。
終わったのかしら。
最後に、子クラスでtryもthrowも書いてみる場合。
public void throwExceptionTryAndThrows() throws Exception{ try { throw new Exception(); } catch (Exception e) { System.out.println("やっぱりtry~catchしました。"); } }
結果
やっぱりtry~catchしました。
お疲れ様でした。
終わったのかしら。