Throwing exception in constructor

Timon Gehr timon.gehr at gmx.ch
Tue Aug 16 10:33:06 PDT 2011


On 08/16/2011 07:08 PM, Stijn Herreman wrote:
> Why is the return statement required, while nothing after the Exception
> is executed?
> Error: one path skips constructor
>
> public this(string p1, string p2, string p3)
> {
> string json = download_string(...);
>
> if (json is null)
> {
> throw new Exception("404");
> writeln("test");
> return;
> }
> else
> {
> this(json);
> }
> }
>
> package this(string json)
> {
> ...
> }

The Exception has no influence, the following code will still get the error:

class JSON{
     public this(string p1, string p2, string p3)
     {
         string json = download_string(...);

         if (json is null)
         {
             ...
         }
         else
         {
             this(json);
         }
     }

     this(string json)
     {
         ...
     }
}

This is afaik by design (described somewhere in TDPL). The idea is that 
a constructor can either construct the value itself in all code paths or 
delegate construction to another constructor in all code paths. The fact 
that the code compiles with return but not with throw is probably a bug.


More information about the Digitalmars-d-learn mailing list