これには必ずしも「正しい」答えがあるとは限らないと思います。おそらくそれはスタイルの問題ですが、try/catch ブロックをどのように構築するのか疑問に思うことがよくあります。
たとえば、以下の架空のコードで概説されている 2 つのメソッド (純粋に説明用) を取り上げます。複数回呼び出す例外をスローするメソッドがありますが、どの呼び出しかによって異なる処理が必要になります。同様に、さまざまなハンドラーでさまざまな種類の例外がスローされる可能性があります。
private Object exceptionMethod() throws Exception {
throw new Exception("Something bad happened");
}
public void useMethodSequentialHandlers() {
Object o1; // Must be declared in a wider scope than where it is used
try {
o1 = exceptionMethod();
} catch (Exception ex) {
// Assume we cannot continue after this exception so we'll return or
// rethrow to exit the method
return;
}
Object o2; // Must be declared in a wider scope than where it is used
// Do something that requires o1
for (int i = 0; i < 100; i++) {
try {
o2 = exceptionMethod();
// Here we would use the objects in some manner
boolean equal = o1.equals(o2);// Just a pointless example
// to show that both objects
// are required
// Assume the method does a load of stuff down here
} catch (Exception ex) {
// Assume we can continue to the next iteration after this exception
continue;
}
}
}
私が見ているように、try/catch ブロックを順番に並べることの利点は、例外に応答している正確な時点が読者にとってより明確であるため、おそらくコードがより明確になることです。欠点は、メソッドのさまざまな場所に例外処理が散らばっていることと、必要以上に広いスコープで宣言された変数があることです (これは悪いことですか?)。
または:
public void useMethodNestedHandlers() {
try {
Object o1 = exceptionMethod(); // Can be declared inside scope where it is used
// Do something that requires o1
for (int i = 0; i < 100; i++) {
try {
Object o2 = exceptionMethod(); // Can be declared inside scope where it is used
// Here we would use the objects in some manner
boolean equal = o1.equals(o2); // Just a pointless example
// to show that both objects
// are required
// Assume the method does a load of stuff down here
} catch (Exception ex) {
// Assume we can continue to the next iteration after this
// exception
continue;
}
}
} catch (Exception ex) {
// Assume we cannot continue after this exception so we'll return or
// rethrow to exit the method
return;
}
}
ここでは、例外処理ロジックをまとめて保持し、変数は使用されるスコープ内で宣言されます。ただし、例外処理ロジックは、発生点から離れているため、あまり明確ではないようです。どちらが良いかについて意見を持っている人はいますか、それとも私は無意味な細かな点について心配しているだけで、仕事を続けるべきですか? :-)
ありがとう