On Tuesday, 21 February 2012 at 14:13:55 UTC, Andrei Alexandrescu wrote:
On 2/21/12 4:48 AM, foobar wrote:
On Tuesday, 21 February 2012 at 02:23:58 UTC, Andrei Alexandrescu wrote:
On 2/20/12 7:02 PM, Juan Manuel Cabo wrote:
oops, sorry!! I just saw a post by someone named Jose. My thousand
apollogies!!

I got confused. It was your argument I meant to refer to - adding info
to the exception in flight.

Andrei

I'd implement this along these lines:

class WithErrorCode(E) : E {
int errorCode;
this(Args)(int err, Args args) { this.errorCode = err; super(args); }
}

and add this wrapper where relevant. e.g. replace:
throw new FileNotFoundException(...);
with something like:
throw new WithErrorCode!FileNotFoundException(-1, ...);

This is a localized change that doesn't affect all uses of exceptions and it remains type-safe. surely this is a better solution than the hash
table?

The two approaches don't compete as one is static and the other is dynamic. For example, how does one add contextual information "While opening table in {database}" to the current exception of type WithErrorCode!FileNotFoundException?


Andrei

This works:
// note: the int parameter above isn't static
dbConn.query("select age from people where id='foobar'");
throw new WithErrorCode!FileNotFoundException(
          db.rs.getValue(1), "file not found");

This approach fails if you don't know ahead of time what *fields* you want to add to your exception but I'd argue that this is unrealistic. An exception is thrown as a response to a specific erroneous condition which means you already know *what* the problem is and what kind of data is needed to describe it.

Can you offer a real world use-case where the above isn't sufficient?

Reply via email to