例外の再送出
ロベールのC++入門講座 10-05
例外が発生して関数を抜ける前に何かしらの後処理がしたい場合、以下のように例外の再送出を使います。
#include <iostream> using std::cout; using std::endl; void func () { int* p = NULL; try { p = new int[10]; throw "エラー発生!"; } catch (...) { // func関数を抜ける前にpのメモリを解放しないといけない delete [] p; cout << "pを解放する" << endl; // エラー処理は呼び出し側に任せたいので再送出 throw; } } int main () { try { func(); } catch (const char* error) { cout << error << endl; } return 0; }
$ main pを解放する エラー発生!
catchブロック内でthrowを引数無しで呼び出すと、そこでcatchした例外の再送出を行ってくれます。
もしcatchブロックではない場所で引数無しthrowを呼び出すとどうなるのでしょうか?
僕の予想ではコンパイルエラーになるのではと思ったのですが処理が通りました。
ただし、実行時にエラーが発生しました。
#include <iostream> using std::cout; using std::endl; int main () { try { throw; } catch (...) { cout << "error" << endl; } return 0; }
$ main This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
どうやらcatchブロック外で引数無しthrowを呼び出すと例外処理ですらキャッチできない例外が発生するようです^^;