Throwing exception in constructor

Stijn Herreman stijn.herreman at telenet.be
Tue Aug 16 10:44:54 PDT 2011


On 16/08/2011 19:33, Timon Gehr wrote:
> 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.
I found the passage you mentioned, you are correct.
I don't, however, understand the reason behind this design.


More information about the Digitalmars-d-learn mailing list