3
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++例外処理入門メモ

Last updated at Posted at 2022-11-10

C++例外処理

https://learn.microsoft.com/en-us/cpp/cpp/errors-and-exception-handling-modern-cpp?view=msvc-170
こちらを参考に例外処理について学習したときのメモ。

基本

  • try (statement) 実行中発生するエラーを補足するブロックを定義する
  • throw (keyword) 問題を検知した際にエラーを投げる
  • catch (statement) tryブロックでエラーが発生した際に実行されるブロックを定義する
try {
    throw (1);
} catch (int error_number) {
    std::cout << "error: " << error_number << std::endl;
}

throw された型が不明な場合、Three dotsで何でもCatchできる。

try {
    throw unknowtype;
} catch(...) {
    // do something
}

Best Practices

throwするエラーはヘッダの標準exceptionを使用するべきである。

try {
    throw std::runtime_error("something wrong");
} catch (std::exception& e) {
    std::cout << e.what() << std::endl;
}

例外をcatchする際は、値ではなく参照でcatchする

発生すべきでないエラーはassertを使うべし

void f(int x) {
  // パラメータxは、正数でなければならない
  assert(x >= 0);
}

C++11で非推奨とされた例外指定を使用しない

動的例外指定C++11で非推奨になった。

まとめ

マイクロソフトのドキュメントは神。
ありがたい。


Special thanks

ご指摘ありがとうございます! 感謝!

3
0
2

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
3
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?