I wanted to ask if it is considered bad form to throw an exception in the constructor? I know that the object will not be fully created, and because of this, leaks are possible. But in my case, I use smart pointers and I need to check the received data in the constructor when creating the system object, if something is not right then throw an exception and exit () there, or can I exit directly in the constructor? I would like to receive a detailed answer to this topic. Thank you in advance...

    1 answer 1

    Is it considered bad form to throw an exception in a constructor?

    No, it does not. Exceptions including in order to provide an emergency exit mechanism for those contexts in which other more or less elegant mechanisms for handling exceptional situations cannot be proposed. Constructors fall into this category (operators are another example). Of course, it is necessary to be able to throw exceptions correctly so that there are no leaks.

    However, deciding whether to throw an exception out of the constructor, or to finally complete the construction of an object in a kind of “suspended” state, is a creative and ambiguous question.

    if something is wrong, then throw an exception and exit () there, or you can exit directly in the constructor

    You have some kind of unconditional obyazannost on exit observed. Throwing and handling exceptions does not necessarily imply the completion of the program. The exception can be caught, processed, recovered after it and continue normal operation.

    But if in your case the occurrence of an exceptional situation necessarily leads to the completion of the entire program, then stitching the unconditional kill of the entire program into the designer of an object is in most cases a bad form. It is better to just throw the exception away, and take the decision on completion at a higher level.

    • to complete the program, simply do not handle the exception - AR Hovsepyan
    • @AR Hovsepyan: Yes, that's enough. But, first of all, not everyone likes what this “uncontrolled” conclusion looks like. Secondly, the language does not guarantee the promotion of the stack, if the exception is not processed, i.e. the release of potentially available captured resources may be crooked or not happen at all. - AnT 5:46 pm
    • Want to say that after calling a terminate (), stack promotion may not occur? . I'm not sure ... - AR Hovsepyan
    • 2
      @AR Hovsepyan: This is openly stated in the standard. (See also stackoverflow.com/questions/44887319/… ). Stack promotion for an unhandled exception is not guaranteed (the decision is made by the implementation). This is done so that the system in such a situation after the program crash could form a full-fledged coredump on the stack that has not yet been promoted. - AnT
    • thanks for the answer. I believe you, because in such matters you are special. I will study the topic in more detail - AR Hovsepyan