例外処理
例外(異常な事象)が発生した場合に実行するプログラムのこと
例外処理の使い方
例外処理は次の3つのキーワードを用いて実装します
try
catch
throw
try
例外が発生する可能性のあるコードをtry{}
で囲う
各try
ブロックには1つ以上のcatch
ブロックが存在する
catch
例外を処理するコードを書きます
catch
に続く()
に例外の型を書きます
throw
例外とその値を送るための構文
サンプルプログラム
#include <iostream>
using namespace std;
int main() {
try
{
throw runtime_error("test");
}
catch(const runtime_error& e)
{
cout << e.what() << endl;
}
return 0;
}
test
例外の型
例外には様々な型が使用できる
#include <iostream>
using namespace std;
int main() {
try
{
throw 10;
}
catch(const int v)
{
cout << v << endl;
}
return 0;
}
10
あらゆる例外をcatch
する
catch(...)
と書くことであらゆる例外をcatchできる
#include <iostream>
using namespace std;
int main() {
try
{
throw runtime_error("test");
}
catch(...)
{
cout << "Unexpected exception was thrown." << endl;
}
return 0;
}
Unexpected exception was thrown.