Throw exception in Constructor

Is it a good idea to throw an exception from a constructor?
What happened if exception throws from a constructor?

Last edited on
After google on this, I found below important points:

1. Constructors don’t have a return type, so it’s not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

2. When the program finds the exception in the constructor, it throws the exception to nearly by catch block [if used] or thrown to the caller (main()).
In below example have catch block in constructor and exception handled by it. Once exception handled, the remaining statements in the constructor/function will be started executing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A
{
  public:
   A(){
        printf("Hi Constructor of A\n");        
   try
   {
        throw 10;
   }
   catch(...)
   {
       printf("the String is unexpected one in constructor\n");
   }
   printf("Hi Constructor of A\n");
 }


Please let me know if there are other thoughts regarding this...
> Is it a good idea to throw an exception from a constructor?
> Please let me know if there are other thoughts regarding this...

"There are domains, such as some hard-real-time systems (think airplane controls) where (without additional tool support) exception handling is not sufficiently predictable from a timing perspective. There the is_valid() technique must be used. In such cases, check is_valid() consistently and immediately to simulate RAII."
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-throw
That said, in non-critical systems it is perfectly valid and/or acceptable and/or reasonable and/or moral to throw from a constructor.

(Unlike the destructor, which should never throw. Though you knew this already from your other thread...)
Thanks JLBorges and Duthomhas.
You guys are really great. :)
Topic archived. No new replies allowed.