Returning data while dying

Ovid on 2007-06-27T14:36:53

Someone asked me about one of their coworkers who wrote something conceptually similar to this:

sub set_and_die {
    $_[0] = 7;
    die "ha!";
}

my $val = 'Ovid';
eval { set_and_die($val) };
print $val;

The actual code is in C# and he throws an exception and sets a value (via an "out" parameter). Then the calling code (on the receiving end of a Web service), has to examine the exception to figure out if the value is safe to use or not (I have visions of huge case statements examining magic variables in "object oriented" code).

Wow. Just wow. You return data or you throw an exception and ne'er the twain shall meet. At least, that's what I thought. Can you think of any reason this wouldn't be a a phenomenally bad idea?


Easy:

Aristotle on 2007-06-27T15:22:26

Job security.

*ducks*

Re:Easy:

Ovid on 2007-06-27T15:27:29

Laughing my @$$ off right now :)

The only thing I can think of is...

btilly on 2007-06-27T19:05:00

that someone is using exceptions for normal flow of control. That's tempting, but it is a bad idea.

Cheers,
Ben

No more expressive than exception objects

brother on 2007-06-27T19:06:23

I would rate it bad because it is unexpected. It is worth to notice that in the general case your output variables is undefined if the function throws an exception.

If you want to return a value in an exceptionish way I would prefere using an Exception object[0] or in perl:

sub foo {
die { value => 42, Exception => 'Beeep' }
}

my $val;
eval { foo() };
if ($@) {
$val = $@->{value};
}

0) No I don't know if C# allows that. Some other languages seems to do.