Exception handling before and after main

后端 未结 4 766
再見小時候
再見小時候 2021-02-15 17:52

Is it possible to handle exceptions in these scenarios:

  1. thrown from constructor before entering main()
  2. thrown from destructor after leaving main()
相关标签:
4条回答
  • 2021-02-15 17:54
    1. You can wrap up your constructor withing a try-catch inside of it.
    2. No, you should never allow exception throwing in a destructor.

    The funny less-known feature of how to embed try-catch in a constructor:

    object::object( int param )
    try
      : optional( initialization )
    {
       // ...
    }
    catch(...)
    {
       // ...
    }
    

    Yes, this is valid C++. The added benefit here is the fact that the try will catch exceptions thrown by the constructors of the data members of the class, even if they're not mentioned in the ctor initializer or there is no ctor initializer:

    struct Throws {
      int answer;
      Throws() : answer(((throw std::runtime_error("whoosh!")), 42)) {}
    };
    
    struct Contains {
      Throws baseball;
      Contains() try {} catch (std::exception& e) { std::cerr << e.what() << '\n'; }
    };
    
    0 讨论(0)
  • 2021-02-15 17:55

    Yes: don't use dangerous global objects!

    0 讨论(0)
  • 2021-02-15 17:57

    Short answer: no.

    Any global object that throws an exception in its constructor will cause an unhandled exception (that is, terminate be called).

    Any class that throws an exception in its destructor is a broken class.

    Using the singleton pattern rather than globals will give you more options.

    0 讨论(0)
  • 2021-02-15 18:11

    It might be possible to set an exception handler before construction / destruction of the objects in question, that one should be able to handle those exceptions.

    For constructors, there's some weird new syntax that allows exceptions to be caught within the constructor. Not sure how that works, and it's not commonly implemented in many compilers.

    For destructors, you have to wrap the content of the destructor in a try { code(); } catch(...) {} block. Which may not always be the desired behavior, depending on what you want to achieve in that destructor.

    0 讨论(0)
提交回复
热议问题