「Java」throwで例外クラスの独自エラーメッセージを表示するサンプル
書式
1.public String getMessage()
getMessageメソッドで設定した文字列を表示しています
2.throw new NullPointerException("エラーメッセージ内容")
使用例
package info;
class TestInfo {
private static final String TT = "ctn";
// メソッドの定義
static void funA() {
String str = "ctn";
if (str.equals(TT)) {
//例外発生し、エラーメッセージをthrow
throw new NullPointerException("例外で発生メッセージ11");
}
}
}
public class ThrowDemo {
public static void main(String[] args) {
try {
TestInfo.funA();
// 例外をキャッチ
} catch (NullPointerException e) {
//getMessageメソッドで設定した文字列を表示する
System.out.println(e.getMessage());
System.out.println(e);
}
}
}
package info;
class TestInfo {
private static final String TT = "ctn";
// メソッドの定義
static void funA() {
String str = "ctn";
if (str.equals(TT)) {
//例外発生し、エラーメッセージをthrow
throw new NullPointerException("例外で発生メッセージ11");
}
}
}
public class ThrowDemo {
public static void main(String[] args) {
try {
TestInfo.funA();
// 例外をキャッチ
} catch (NullPointerException e) {
//getMessageメソッドで設定した文字列を表示する
System.out.println(e.getMessage());
System.out.println(e);
}
}
}
package info; class TestInfo { private static final String TT = "ctn"; // メソッドの定義 static void funA() { String str = "ctn"; if (str.equals(TT)) { //例外発生し、エラーメッセージをthrow throw new NullPointerException("例外で発生メッセージ11"); } } } public class ThrowDemo { public static void main(String[] args) { try { TestInfo.funA(); // 例外をキャッチ } catch (NullPointerException e) { //getMessageメソッドで設定した文字列を表示する System.out.println(e.getMessage()); System.out.println(e); } } }
実行結果
例外で発生メッセージ11
java.lang.NullPointerException: 例外で発生メッセージ11