28. 数値表現形式の追加
• バイナリ表記
• 2進数表記の追加
int a = 0b011001;
System.out.println(a); //25
• アンダースコア表記
• _で分割して表記
• 先頭と最後にはNG
long a = 123_456_789;
System.out.println(a); //123456789
long b = 0b011_001; //バイナリ表記との合わせ技
System.out.println(b); //25
int c = _123_456 //コンパイルエラー
29. 例外のマルチキャッチ(1)
• 複数の例外を1つのcatchブロックでキャッチ
class ExceptionA extends Exception{}
class ExceptionB extends Exception{}
class MultiCatch {
public static void test(int a) {
try {
if(a == 1) {
throw new ExceptionA();
} else {
throw new ExceptionB();
}
} catch(ExceptionA | ExceptionB ex) {
System.out.println(ex.getClass());
}
}
}
30. 例外のマルチキャッチ(2)
• 例外に継承関係がある場合は注意
• 標準例外の継承関係が曖昧だとハマる
class ExceptionA extends Exception{}
class ExceptionB extends ExceptionA{}
class MultiCatch {
public static void test(int a) {
try {
if(a == 1) {
throw new ExceptionA();
} else {
throw new ExceptionB();
}
} catch(ExceptionB | ExceptionA ex) { //コンパイルエラー
System.out.println(ex.getClass());
}
}
}
31. 例外の再送(1)
• tryブロック中にcatchした例外を再送する
• Java6とかだと・・・
class ReThrowTest {
public static void test(int a) throws Exception {
try {
if(a == 1) {
throws ExceptionA, ExceptionB
throw new ExceptionA();
とか書けない!
} else {
throw new ExceptionB();
}
} catch(Exception ex) {
System.out.println(ex.getClass());
throw ex;
}
}
}
32. 例外の再送(2)
• Java7では
class ReThrowTest {
public static void test(int a) throws ExceptionA, ExceptionB {
try {
if(a == 1) { メソッドが本来throwsしたい
throw new ExceptionA();
例外を記述できる
} else {
throw new ExceptionB();
}
} catch(Exception ex) {
System.out.println(ex.getClass());
throw ex;
}
}
}
33. ジェネリクスの<>記法
• <> = ダイヤモンド
Map<String, Object> map1 = new
HashMap<String, Object>();
Map<String, Map<String, Object>> map2 =
new HashMap<String, Map<String,
Object>>
• Mapとかでネストすると、右辺が冗長!
Map<String, Object> map1 =
new HashMap<>();
Map<String, Map<String, Object>> map2 =
new HashMap<>();