■例外的状況の報告(例外を投げる)
throw 例外インスタンス;
一般的には「throw new 例外クラス名("エラーメッセージ");」となる
■Test05.java
public class Test05 {
public static void main(String[] args) {
Person p = new Person();
p.setAge(-128);
}
}
■Person.java
public class Person {
int age;
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年齢は正の数を指定すべきです。指定値=" + age);
}
this.age = age;
}
}
■実行結果
Exception in thread "main" java.lang.IllegalArgumentException: 年齢は正の数を指定すべきです。指定値=-128
at Person.setAge(Person.java:7)
at Test05.main(Test05.java:4)
■例② Test05.java
public class Test05 {
public static void main(String[] args) {
Person p = new Person();
p.setAge(5);
}
}
■例② Person.java
public class Person {
int age;
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("年齢は正の数を指定すべきです。指定値=" + age);
}
this.age = age;
System.out.println("異常なし");
}
}
■例② 実行結果
異常なし
■例外インスタンスが必ず備えているメソッド
String getMessage()
例外的状況の解説文(エラーメッセージ)を取得する
■String getMessage() 例
■Test05.java
public class Test05 {
public static void main(String[] args) {
try {
throw new UnsupportedMusicFileException("未対応のファイルです");
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
■UnsupportedMusicFileException.java
public class UnsupportedMusicFileException extends Exception {
public UnsupportedMusicFileException(String msg) {
super(msg);
}
}
■String getMessage() 例 実行結果
未対応のファイルです
void printStackTrace()
スタックトレース(エラーが発生するまでの経緯)の内容を画面に出力する
■printStackTrace()例
■Test05.java
public class Test05 {
public static void main(String[] args) {
try {
throw new UnsupportedMusicFileException("未対応のファイルです");
} catch (Exception e) {
e.printStackTrace();
// System.out.println(e.getMessage());
}
}
}
■UnsupportedMusicFileException.java
public class UnsupportedMusicFileException extends Exception {
public UnsupportedMusicFileException(String msg) {
super(msg);
}
}
■printStackTrace()例 実行結果
UnsupportedMusicFileException: 未対応のファイルです
at Test05.main(Test05.java:4)