35. 例外定義
35. 例外定義
独自の例外を定義
l:\lesson087\test.java
class test { public static void main(String args[]) { try { ThrowException(); } catch (Exception err) { System.out.println(err); } } static void ThrowException() throws MyException { throw new MyException("ThrowException() の例外"); } } class MyException extends Exception { public MyException(String msg) { super(msg); } }
実行結果
L:\lesson087>java test
MyException: ThrowException() の例外
例外の可能性を報告
l:\lesson088\test.java
class test { public static void main(String args[]) throws MyException { ThrowException(); } static void ThrowException() throws MyException { throw new MyException("ThrowException() の例外"); } } class MyException extends Exception { public MyException(String msg) { super(msg); } }
実行結果
L:\lesson088>java test
Exception in thread "main" MyException: ThrowException() の例外
at test.ThrowException(test.java:7)
at test.main(test.java:3)