2016-10-14 15 views
-2

特定の例外を捕捉して処理しようとしていて、例外を処理するコードを実行する汎用例外をスローしています。これはどのように達成されますか?このスニペットはExceptionをキャッチしていないので、出力がcatchブロック内で例外をスローする

Exception in thread "main" java.lang.Exception 
    at Main.main(Main.java:10) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) 
IOException specific handling 

Process finished with exit code 1 

抜粋です:

import java.io.IOException; 

public class Main { 

    public static void main(String[] args) throws Exception { 
     try { 
     throw new IOException(); 
     } catch (IOException re) { 
     System.out.println("IOException specific handling"); 
     throw new Exception(); 
     } catch (Exception e) { 
     System.out.println("Generic handling for IOException and all other exceptions"); 
     } 
    } 
} 
+4

[catchブロック内にスローされた例外 - 再び捕捉されるのでしょうか?](http://stackoverflow.com/questions/143622/exception-thrown-inside-catch-block-will-it-be-caught-もう一度) –

+0

これはどのように失敗するのですか? '' IOException specific handling "'というメッセージが出力されたため、あなたは 'catch'ブロックに達しました。その後、アプリケーションは例外で終了しました。なぜなら、あなたは*例外を投げたからです。 – David

+0

@David Exceptionブロック内のコードを実行したい。 – newToScala

答えて

1

あなたがのIOExceptionのキャッチブロックを投げる例外がキャッチされることはありません。そのため、メインメソッドに「例外をスローする」を追加する必要があります。

同じtryの後で複数のcatch-blockがif..elseカスケードのように振る舞い、特定の例外を処理するのに適したcatchブロックを探す。

埋め込み別のtry..catchブロックで全体のtry..catch:あなたは、最終的な例外処理(の緩い情報はないように

try { 
    try { 
    throw new IOException(); 
    } catch (IOException re) { 
    System.out.println("IOException specific handling"); 
    throw new Exception(); 
    } 
} catch (Exception e) { 
    System.out.println("Generic handling for IOException and all other xceptions"); 
    } 

通常1は、新しい汎用的な例外で元の例外を埋め込みます例えば、あなたは正確に例外が発生した場所)を識別するためにスタックトレースをログに記録する場合:

throw new Exception(re); 

と、最終的なキャッチブロック内:

e.printStackTrace(); 
関連する問題