私のメソッドthrows節で例外を宣言して呼び出し側チェーンの上に例外を渡すことが何を意味するのか、そしてなぜそれをやりたいのかについての説明が望まれました。呼び出し側チェーンの例外を渡す
ここに、自分の例外をスローすることを理解した例があります。
public class ExceptionThrow {
char[] charArray = new char[] { 'c', 'e', 'a', 'd' };
void checkArray() throws ABException {
for (int i = 0; i < charArray.length; i++) {
switch (charArray[i]) {
case 'a':
throw new ABException();
case 'b':
throw new ABException();// creating the instance of the
// exception anticipated
default:
System.out.println(charArray[i] + " is not A or a B");
}
}
}
public static void main(String[] args) {
ExceptionThrow et = new ExceptionThrow();
try {
et.checkArray();
} catch (ABException ab) {
System.out.println(ab.getMessage() + " An exception did actually occur");
} finally {
System.out.println("This block will always execute");
}
}
}
class ABException extends Exception {
}
「コールチェーンの上に」例外をどのように渡しますか?
よろしく アリウス
+1明確な説明があります。追加する小さなものが1つあります。例外のスタックトレースを見たい場合は、 'printStackTrace()'メソッドを呼び出すことができます。 'try {...} catch(例外e){e.printStackTrace();} } ' – THelper
THELPER、あなたが間違っていると言っているのではありませんが、これらの(例外をバブリングする)状況でe.printStackTrace()を使うのは悪い習慣だと思います。テストやもののためにそれを使用するのは大丈夫です。これは、不要なスタックトレースをログファイルに残すためです。特に、例外が上位層で処理されている場合、現在のコンテキストでは意味を持たないスタックトレースでログを汚染するのはなぜですか。 – Amit