• C++语法之function-try-block


    C++里边有个看着比较怪异的语法,叫做“function-try-block”。见下面代码示例中的普通函数和构造函数的用法。另外析构函数也支持这种用法。

    个人不觉得这个用法很赞,主要是因为它的行为比较复杂,对于普通函数和构造函数析构函数在到达catch-block结尾时候的行为不太一致,可以认为是比较坑猿的。

    另外这个特性在C++98的时候就已经存在了,所以示例代码特意没有使用C++11或更高版本的语法。

    1. #include <iostream>
    2. #include <exception>
    3. // Demonstration of function-try-block
    4. // See Also:
    5. // https://en.cppreference.com/w/cpp/language/function-try-block
    6. class SomeException : public std::exception
    7. {
    8. private:
    9. std::string message;
    10. public:
    11. SomeException (const char * msg) : message(msg)
    12. {
    13. }
    14. virtual ~SomeException() _NOEXCEPT /* use noexcept in C++11 */
    15. {
    16. }
    17. virtual const char* what() const _NOEXCEPT /* use noexcept in C++11 */ {
    18. return message.c_str();
    19. }
    20. };
    21. void foo () {
    22. std::cout << "simple foo function" << std::endl;
    23. }
    24. void bar() {
    25. std::cout << "evil bar function" << std::endl;
    26. throw SomeException("Some exception in bar");
    27. }
    28. void tryfunction (int i=0)
    29. try {
    30. foo();
    31. bar();
    32. } catch(const std::exception & e) {
    33. std::cout << "something was wrong - " << e.what() << std::endl;
    34. std::cout << "i = " << i << std::endl;
    35. }
    36. class EvilBase
    37. {
    38. public:
    39. EvilBase () {
    40. throw SomeException("dark side of the force");
    41. }
    42. virtual ~EvilBase () {
    43. }
    44. };
    45. class InnocentDerived : public EvilBase
    46. {
    47. public:
    48. InnocentDerived() try : EvilBase(), m(1)
    49. {
    50. // other initializations
    51. } catch (const std::exception & e) {
    52. std::cerr << "what is the problem? " << e.what() << std::endl;
    53. } // the current exception is rethrown here
    54. private:
    55. int m;
    56. };
    57. int main() {
    58. tryfunction();
    59. InnocentDerived d;
    60. }

    讲代码保存为文件tryfunction.cpp,编译命令如下:

    `$ g++ -std=c++98 tryfunction.cpp -o ./a1`

  • 相关阅读:
    9月5日关键点检测学习笔记——人体骨骼点检测:自顶向下
    RPC - gRPC简单的demo - 学习/实践
    嵌入式分享合集105
    力扣算法入门刷题
    Linux常用命令学习
    备忘录模式 行为型模式之八
    「网页开发|前端开发|Vue」07 前后端分离:如何在Vue中请求外部数据
    【c++设计模式之中介者模式】分析及示例
    uniapp地图组件(map)使用问题总结
    基于FPGA的ECG信号采集,存储以及传输系统verilog实现
  • 原文地址:https://blog.csdn.net/IDisposable/article/details/125530276