手順
1. Javaプロジェクトを右クリックし、[New]-[Package]で、[New Java Package]ダイアログを表示
2. パッケージ名をを入力(ここでは、「CustomExceptions」とする)し、[Finish]ボタンを押下
3. Javaプロジェクトを右クリックし、[New]-[Class]で、[New Java Class]ダイアログを表示
4. クラス名をを入力(ここでは、「CustomException」とする)
5. [Superclass]欄の[Browse_]ボタンを押下し、[Superclass Selection]ダイアログを表示
6. [Choose a type]欄に「Exception」と入力し、[OK]ボタンをクリック
7[New Java Class]ダイアログの[Superclass]欄に「java.lang.Exception」が
自動入力されていることを確認し、[Finish]ボタンを押下
8. 以下のように、mainメソッドを生成していないことを確認
例
package CustomExceptions;
public class CustomException extends Exception {
}
サンプル
CustomException.java
独自例外クラス
package CustomExceptions;
public class CustomException extends Exception { // ☆★例外を継承★☆
private static final long serialVersionUID = 1L;
private int code;
public CustomException(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}
callCustomException.java
独自例外を組み込んだ自作ライブラリ
package CustomExceptions;
public class callCustomException {
public callCustomException() {
}
public void callException(int code, String message)
throws CustomException { // ☆★例外を投げることを指定★☆
if (code < 0) {
throw new CustomException(code, message); // ☆★ここで受け取って、例外を投げる(newしている)★☆
}
return;
}
}
studyMain.java
メイン
import CustomExceptions.*;
public class studyMain {
public static void main(String args[]) {
callCustomException obj = new callCustomException();
try {
obj.callException(-1, "Don't call me!!" ); // ☆★無理やり呼ぶ★☆
} catch (CustomException e) {
e.printStackTrace();
}
return;
}
}
出力
CustomExceptions.CustomException: Don't call me!!
at CustomExceptions.callCustomException.callException(callCustomException.java:11)
at studyMain.main(studyMain.java:7)