class CustomExceptionA extends Exception {
public CustomExceptionA(String message) {
super(message);
}
}
class CustomExceptionB extends Exception {
public CustomExceptionB(String message) {
super(message);
}
}
public class ExceptionChainingExample {
public static void main(String[] args) {
try {
// メソッドCを呼ã³å‡ºã—ã¦ä¾‹å¤–ã®ãƒã‚§ãƒ¼ãƒ³ã‚’発生ã•ã›ã‚‹
methodC();
} catch (CustomExceptionA finalException) {
// 最終的ã«ã‚ャッãƒã•れる例外を表示
System.out.println("最終的ãªä¾‹å¤–ãŒã‚ャッãƒã•れã¾ã—ãŸã€‚");
finalException.printStackTrace();
}
}
// メソッドA
static void methodA() throws CustomExceptionA {
throw new CustomExceptionA("CustomExceptionA ãŒç™ºç”Ÿã—ã¾ã—ãŸã€‚");
}
// メソッドB
static void methodB() throws CustomExceptionB {
throw new CustomExceptionB("CustomExceptionB ãŒç™ºç”Ÿã—ã¾ã—ãŸã€‚");
}
// メソッドC
static void methodC() throws CustomExceptionA {
try {
// メソッドAを呼ã³å‡ºã™
methodA();
} catch (CustomExceptionA exceptionA) {
try {
// メソッドBを呼ã³å‡ºã—ã€initCauseメソッドã§ä¾‹å¤–ã®ãƒã‚§ãƒ¼ãƒ³ã‚’構築
methodB();
exceptionA.initCause(new CustomExceptionB("CustomExceptionB ㌠CustomExceptionA ã«ãƒã‚§ãƒ¼ãƒ³ã•れã¾ã—ãŸã€‚"));
} catch (CustomExceptionB exceptionB) {
// 例外BãŒç™ºç”Ÿã—ãŸå ´åˆã¯ã€ä¾‹å¤–Aをスãƒãƒ¼
throw exceptionA;
}
}
}
}
ã“ã®ãƒ—ãƒã‚°ãƒ©ãƒ ã§ã¯ã€methodC 内ã§ã¾ãš methodA を呼ã³å‡ºã—ã€ãã®ä¾‹å¤–ãŒæ•æ‰ã•れãŸã‚‰ methodB を呼ã³å‡ºã—ã€initCause メソッドを使用ã—ã¦ä¾‹å¤–ã®ãƒã‚§ãƒ¼ãƒ³ã‚’構築ã—ã¦ã„ã¾ã™ã€‚最終的ã«ã€CustomExceptionB ㌠CustomExceptionA ã«ãƒã‚§ãƒ¼ãƒ³ã•れãŸä¾‹å¤–㌠main メソッドã§ã‚ャッãƒã•れã€ã‚¹ã‚¿ãƒƒã‚¯ãƒˆãƒ¬ãƒ¼ã‚¹ãŒè¡¨ç¤ºã•れã¾ã™ã€‚
「019 例外ã¨ä¾‹å¤–処ç†ã€å•題集リスト
🎯 実習ã§ç†è§£ã‚’æ·±ã‚よã†
ã“ã®å†…容ã«ã¤ã„ã¦JavaDrillã§å®Ÿéš›ã«æ‰‹ã‚’å‹•ã‹ã—ã¦å¦ç¿’ã§ãã¾ã™


コメント