Is it possible to throw an exception through a constructor?

Yes, we can! We cannot return any error value from the constructor, as the constructor doesn’t have any return type. In such situation, by throwing an exception we can pass value to catch block. 

This is shown in the following example:
#include <iostream.h>
class sample
{
     public:
           sample ( int i )
           {
                 if ( i == 0 ) throw "error"; 
           } 
};
void main( )
{
     try
     {
          sample s ( 0 );
     }
     catch ( char * str ) 
     {
          cout << str; 
     }

1 comment: