2017-01-03 17 views
0

メソッドが必要です。methodC1()で例外があっても、C2も実行されます。ここでは、methodC1()とmethodC2()という2つのメソッドしか追加していません。多くの方法があるとしましょう。その場合にも、解決策は適用可能でなければならない。すべての行終了後のハンドル例外

abstract class A { 
     abstract String methodC1() throws ExceptionE; 
     abstract String methodC2() throws ExceptionE; 

     protected String methodA() throws ExceptionE2 { 
      try { 
       methodC1(); 
       methodC2(); 
      } catch (ExceptionE e) { 
       throw new ExceptionE2(); 
      } 
     } 
    } 

    class C extends A { 
     String methodC1() throws ExceptionE { 
      // do something 
     } 

     String methodC2() throws ExceptionE { 
      // do something 
     } 
    } 
+0

'methodC2'が' methodC1'とは異なる例外を投げるとどうなりますか? – Azodious

+0

最終的にブロックに入れてください。 – Januson

+0

各メソッドの実装でtry catchを使用し、そのメソッドのみを処理するか、メソッドを呼び出すときに各メソッドに対してtry catchを使用します –

答えて

0

はここに1つの方法です:両方の例外をスローしmethodC1methodC2場合

protected String methodA() throws ExceptionE2 { 
try { 
    methodC1(); 
} catch (ExceptionE e) { 
    throw new ExceptionE2();  // HERE 
} finally { 
    try { 
     methodC2(); 
    } catch (ExceptionE e) { 
     throw new ExceptionE2(); // THERE 
    } 
} 

methodAから伝播ExceptionE2finallyブロック内でスローずつです。すなわち// THERE最初のもの(// HEREが投じられたもの)が「食べられる」。

この要件に対処する他の方法もありますが、これは最も簡単で、methodC1methodC2の署名を変更する必要はありません。あなたは両方のExceptionE例外からのエラー情報を符号化し、例外を伝播する必要がある場合は


、その後、あなたはそれが複数の例外をラップすることができるようにExceptionE2を再設計する必要があるとしています。 (2つの例外は、Javaで同時に伝播されることは...できませんまたは任意の他のプログラミング言語では、私が知っています。)

は、最終的な結果は次のようになります。

protected String methodA() throws ExceptionE2 { 
    List<ExceptionE> exceptions = new ArrayList<>(); 
    try { 
     methodC1(); 
    } catch (ExceptionE e) { 
     exceptions.add(e); 
    } 
    try { 
     methodC2(); 
    } catch (ExceptionE e) { 
     exceptions.add(e); 
    } 
    if (!exceptions.isEmpty()) { 
     throw new ExceptionE2(exceptions); 
    } 
} 
0

通常、同じ方法の例外から回復する必要はありません。

本当に必要な場合は、ビジネスロジックと例外処理を共有できるように、できるだけ多くのメソッドを他のメソッドにパックすることができます。 たとえば、上記の方法が失敗した場合、メソッドを実行しないでください。

また、各メソッドを独自のtry catchで持つことで、実行を継続できます。

また、forループで実行するための実行リストを作成することもできます。

0

代わりにthrows ExceptionEを使用しないでください。メソッドcatch1とmethodc2でtry catchブロックを使用してください。

abstract class A { 
    abstract String methodC1(); 
    abstract String methodC2(); 

    protected String methodA(){ 
     methodC1(); 
     methodC2(); 
    } 
} 

class C extends A { 
    String methodC1() { 
     try{ 
      //code 
     } catch (ExceptionE e) { 
      //handle exception 
     } 
    } 

    String methodC2() { 
     try{ 
      //code 
     } catch (ExceptionE e) { 
      //handle exception 
     } 
    } 
} 
0

を最後にブロックを追加しますあなたの試合にあなたの問題を解決する必要があります。最後に、キャッチブロック内の操作の結果が何であっても呼び出されます。

try{ 
    methodC1(); 
} 
catch(ExceptionE e){ 
    throw new ExceptionE2(); 
} 
finally{ 
    methodC2(); 
}