これらは 2 つの異なるものです。
- catch ブロックは、try ブロックで例外がスローされた場合にのみ実行されます。
- 例外がスローされたかどうかにかかわらず、finally ブロックは常に try(-catch) ブロックの後に実行されます。
あなたの例では、3番目の可能な構成を示していません:
try {
// try to execute this statements...
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
// ... more catches for specific exceptions can come here
catch( Exception e ) {
// if a more general exception was thrown, handle it here
}
finally {
// here you can clean things up afterwards
}
そして、@codeca がコメントで述べているように、finally ブロックは例外がなくても実行されるため、finally ブロック内の例外にアクセスする方法はありません。
もちろん、ブロック外で例外を保持する変数を宣言し、catch ブロック内で値を代入することもできます。その後、finally ブロック内でこの変数にアクセスできます。
Throwable throwable = null;
try {
// do some stuff
}
catch( Throwable e ) {
throwable = e;
}
finally {
if( throwable != null ) {
// handle it
}
}