Throwing exception in constructor
Vijay Nayar
madric at gmail.com
Tue Aug 16 10:39:48 PDT 2011
On Tue, 16 Aug 2011 19:33:06 +0200, 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.
Well I'll be a monkey's uncle. I tried it out and sure enough you are
correct. I'm still reading TDPL, and now I'm curious to find the
rationale.
public this(string value) {
if (value == "Hambo") {
_value = 999;
} else {
this(to!int(value));
}
}
More information about the Digitalmars-d-learn
mailing list