16
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C++良すぎる 特にtry文

Last updated at Posted at 2025-12-22

try「ブロック」の話ですか?

ご本家

tryブロック

try { /* … */ } catch (/* … */) { /* … */ }

このようなC++の例外処理の構文は、tryブロックといいます。
try文とはいいません。

規格書の try block をtryブロックと訳すなら、tryブロックは文ではありません
try block は try-blockfunction-try-block のことであり、 try-block は文ですが、 function-try-block は文ではありません。
紛らわしいですが、 try-block は文で、 try block は文とは限りません。

A try-block is a statement. [Note: Within this Clause “try block” is taken to mean both try-block and function-try-block. — end note]
https://eel.is/c++draft/except.pre#2

try-block

try-block:
try compound-statement handler-seq
handler-seq:
handler handler-seqopt
handler:
catch ( exception-declaration ) compound-statement
exception-declaration:
attribute-specifier-seqopt type-specifier-seq declarator
attribute-specifier-seqopt type-specifier-seq abstract-declaratoropt
...

try-block はみなさんご存知の構文です。
特に説明はしません。

function-try-block

function-try-block:
try ctor-initializeropt compound-statement handler-seq

function-try-block は try block を関数の本体として使うときの構文です。

#include <print>

int main()
try {
    throw 0;
}
catch (...) {
    std::println("Hello, try block!");
}

try-block と違って、 try の後に ctor-initializer: とメンバ初期化子リスト)が書けます。
クラスのコンストラクタの本体に function-try-block を使うと、メンバ変数初期化中や委譲コンストラクタ実行中の例外を補足してくれます(存在意義)。

#include <print>

struct A {
    A() { throw "exception from A()"; }
    A(int) { throw "exception from A(int)"; }
};

struct B {
    A a;

    B()
    try {}
    catch (const char* s) {
        std::println("In B(), catch {}.", s);
    }

    B(int x)
    try : a(x) {}
    catch (const char* s) {
        std::println("In B(int), catch {}.", s);
    }
};

int main() {
    try {
        B b;
    }
    catch (const char* s) {
        std::println("Also in main(), catch {}.", s);
    }
    try {
        B b(42);
    }
    catch (const char* s) {
        std::println("Also in main(), catch {}.", s);
    }
}
In B(), catch exception from A().
Also in main(), catch exception from A().
In B(int), catch exception from A(int).
Also in main(), catch exception from A(int).

おわり

おわりです。
バズりに乗っかりたかっただけです。

16
1
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
16
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?