首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Function-try-block

在函数体周围建立异常处理程序。

句法

函数尝试块是函数体的另一种语法形式,它是功能定义...

try ctor-initializer(optional) compound-statement handler-sequence

?

?

ctor-initializer

-

member initializer list, only allowed in constructors

compound-statement

-

the brace-enclosed sequence of statements that constututes the body of a function

handler-sequence

-

sequence of one or more catch-clauses

解释

功能试块将一系列CATCH子句与整个函数体以及成员初始化列表%28(如果在构造函数%29中也使用)。从函数体中的任何语句引发的每个异常,或从任何成员或基构造函数中引发的构造函数%29,或来自任何成员或基析构函数的%28,都会将控制权传递给处理程序--就像常规抛出的异常一样。试块会的。

二次

代码语言:javascript
复制
struct S {
    std::string m;
    S(const std::string& arg) try : m(arg, 100) {
        std::cout << "constructed, mn = " << m << '\n';
    } catch(const std::exception& e) {
        std::cerr << "arg=" << arg << " failed: " << e.what() << '\n';
    } // implicit throw; here
};

二次

在输入构造函数上的函数尝试块的CATCH子句之前,所有完全构造的成员和基都已被销毁。

If the function-try-block is on a delegating constructor, which called a non-delegating constructor that completed successfully, but then the body of the delegating constructor throws, the destructor of this object will be completed before any catch clauses of the function-try-block are entered.

(since C++11)

在输入析构函数上的函数-尝试-块的任何CATCH子句之前,所有基和非变体成员都已被销毁。

如果用于构造函数或析构函数的函数尝试块的CATCH子句访问对象的基成员或非静态成员,则该行为是未定义的。

构造函数的函数尝试块中的每个CATCH子句都必须通过抛出异常来终止。如果控件到达该处理程序的末尾,则当前异常将自动重新引发,就像throw;.在构造函数%27s函数尝试块的CATCH子句中不允许返回语句.

在析构函数上到达函数-try-块的CATCH子句的末尾时,还会自动重新抛出当前异常,就像throw;,但是允许返回语句。

对于所有其他函数,到达CATCH子句的结尾等于return;如果函数%27s返回类型为%28,则可能是cv限定%29。void,否则行为就没有定义。

注记

函数尝试块的主要目的是记录或修改,然后在构造函数中重新抛出成员初始化程序列表中引发的异常。它们很少与析构函数或常规函数一起使用。

Function-try-Block不捕获由复制/移动构造函数引发的异常,以及通过值传递的函数参数的析构函数:这些异常是在调用方的上下文中抛出的。

Function-try-block of the top-level function of a thread does not catch the exceptions thrown from the constructors and destructors of thread-local objects (except for the constructors of function-scoped thread-locals).

(since C++11)

同样,函数-try-块的主%28%29功能的构造函数和析构函数引发的异常。静态对象%28,除了函数的构造函数-局部静力学%29。

范围函数参数的生存期为%28,但函数本身中声明的对象为%29,扩展到处理程序序列的末尾。

二次

代码语言:javascript
复制
int f(int n = 2) try {
   ++n; // increments the function parameter
   throw n;
} catch(...) {
   ++n; // n is in scope and still refers to the function parameter
   assert(n == 4);
   return n;
}

二次

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com