What's the best technique for exiting from a constructor on an error condition in C++

后端 未结 8 841
北荒
北荒 2020-12-14 08:21

What\'s the best technique for exiting from a constructor on an error condition in C++? In particular, this is an error opening a file.

Thanks for the responses. I\'

相关标签:
8条回答
  • 2020-12-14 08:46

    There is only 1 good way to exit from a constructor that is in error, that is to raise an exception.

    Is it really an error? are you trying to add too much to the constructor?

    Often people will try and roll in some initial interaction into the constructor, like adding the filename to a file constructor. Do you expect it to open that file right away or are you just setting some state, is it different to file.open(filename), is it ok if it fails?

    0 讨论(0)
  • 2020-12-14 08:48

    If you object after the error can not perform its actions - you have to throw. If it can - log you error and change the construction logic.

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