SJC-P 例外
ナビゲーションに移動
検索に移動
SJC-P 例外
次のいずれかがスローされる結果になる状況を認識できる。
- ArrayIndexOutOfBoundsException
- ClassCastException
- IllegalArgumentException
- IllegalStateException
- NullPointerException
- NumberFormatException
- AssertionError
- ExceptionInInitializerError
- StackOverflowError
- NoClassDefFoundError
これらのうちのどれが仮想マシンでスローされるかを知っており、その他については、プログラムでスローすべき状況を認識できる。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExceptionTest {
public static void main(String[] args) {
/*
* ArrayIndexOutOfBoundsException
* 不正なインデックスを使って配列がアクセスされた
* インデックスが負または、配列のサイズ以上
*/
try {
int[] ary = {1,2,3,5};
System.out.println(ary[-1]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
/*
* ClassCastException
* オブジェクトを継承関係にないクラスにキャストしようとした
*/
try {
Object o = new Integer(10);
String s = (String)o;
} catch (ClassCastException e) {
e.printStackTrace();
}
/*
* IllegalArgumentException
* 不正な引数、または不適切な引数をメソッドに渡した
*/
try {
String key = "";
System.out.println(System.getProperty(key));
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
/*
* IllegalStateException
* 不正または不適切なときにメソッドが呼び出された
*/
try {
Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher("012345abcde");
// m.find();
System.out.println(m.start());
} catch (IllegalStateException e) {
// マッチが行われていない、または前回のマッチ操作が失敗
e.printStackTrace();
}
/*
* NullPointerException
* null オブジェクトのインスタンスメソッドの呼び出し
* null オブジェクトのフィールドに対するアクセスまたは変更
* null の長さを配列であるかのように取得
* null のスロットを配列であるかのようにアクセスまたは修正
* null を Throwable 値であるかのようにスロー
*/
try {
Exception e = null;
throw e;
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
/*
* NumberFormatException
* 文字列を数値型に変換しようとしたとき、文字列の形式が正しくない
*/
try {
int i = Integer.parseInt("abc");
} catch (NumberFormatException e) {
e.printStackTrace();
}
/*
* ExceptionInInitializerError
* static 初期化子で予想外の例外が発生したことを通知
*/
try {
ExceptionInInitializerTest t = new ExceptionInInitializerTest();
} catch (ExceptionInInitializerError e) {
e.printStackTrace();
}
/*
* StackOverflowError
* アプリケーションでの再帰の回数が多すぎてスタックオーバーフローが起こる場合にスロー
*/
try {
StackOverFlowTest t = new StackOverFlowTest();
t.funcA();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}
class ExceptionInInitializerTest {
static {
int i = Integer.parseInt("abc");
}
}
class StackOverFlowTest {
public void funcA() { funcA(); }
}
{{include_html banner_html, "!SJC-P"}}
© 2006 矢木浩人