1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ㉓~例外処理~

Posted at

例外処理

例外(異常な事象)が発生した場合に実行するプログラムのこと

例外処理の使い方

例外処理は次の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.
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?