0

次のコードがあります。

 method1() throws Exception{
 //throws an Exception
 }

 method2() throws Exception{
    method1();
    //do something
 }

 method3() throws Exception{
     method2();
     //do something
 }

 method4() throws Exception{
   try{
       method3();
       //do something
    }catch(Exception e){
       //catch exception
     } 
  }

method1() で例外が発生すると、method4() までバブルアップし、そこでキャッチされます。

しかし、これに似た質問に対するいくつかの回答で、例外が次の方法でスローされていることがわかりました。

 method1() throws Exception{
   //throws an Exception
 }

 method2() throws Exception{
    try{
       method1();
    }catch(Exception e){
        throw e;
    }
  }

例外を再スローする最良の方法は何ですか? なぜそれが良いのですか?

「例外処理」のベスト プラクティスについて私が読んだ記事では、早い段階でスローし、遅い段階でキャッチするように書かれています。内部メソッドから可能な限り Exception を再スローする必要があるということですか?

method1() が SQLException をスローした場合、それを method4() でのみキャッチするか、method1() 自体で処理する必要がありますか?

更新: method1() で例外が発生した場合、UI にメッセージを表示したいとします。次に、解決策は何ですか?バブルアップするか、問題を示す値を返す必要がありますか?

method4() は、UI に何らかのメッセージを表示します。

4

1 に答える 1

1

Just throwing the exception with throw e; doesn't seem reasonable to me. Use throw if you have declared an own exception class that encapsulates a set of several basic exceptions. Or use it, if your program detects invalidate (business) data, that wouldn't cause an exception itself.

In addition I would try to reduce the number of throw declarations in methods. It's better to make the code more robust against any sorts of exceptions than having lots of exceptions and try catch blocks. Explicitely bubbling an exception all the way up (using throw) makes the program longer and less readable.

Whenever possible, try to process an exception; e.g. if the user tries to open a non existing file, show a warning and return a value, that shows the parent process that something failed.

Throw early means: your methods should validate input data as early as possible and throw a runtime exception, if something is not as specified. Catch late means not at least: avoid catching exceptions, if you can't do anything about it. Let them ratherly bubble up and log them or notify the user (depends on the system)

Check the difference between Exception and RuntimeException too.

于 2013-03-07T22:27:22.417 に答える