The Right Approach to Exceptions
H. S. Teoh
hsteoh at quickfur.ath.cx
Mon Feb 20 10:42:12 PST 2012
On Mon, Feb 20, 2012 at 01:23:04PM -0500, Jonathan M Davis wrote:
> On Monday, February 20, 2012 11:57:07 Andrei Alexandrescu wrote:
[...]
> > Exactly. I don't see how a disagreement follows from here. So isn't
> > it reasonable to design the exception such that it can offer
> > information pertaining to what went wrong, in a uniform manner?
[...]
> I don't see how you could possibly make that uniform. It's very
> non-uniform by its very nature. The handling _needs_ to be
> non-uniform.
I think there's a misunderstanding here. What Andrei is trying to
achieve is something like this:
class Exception : Error {
Variant[string] data;
string formatMsg(LocaleInfo li) {
return formatLocale(li, msg, data);
}
}
class GetOptException : Exception {
this() {
data["..."] = ...;
...
}
}
I contend that using Variant here is not necessary. You can easily do
this instead:
class Exception : Error {
string formatMsg(LocaleInfo li) {
auto members = typeid(this).getMembers(null);
string msg;
foreach (member; members) {
if (member.name.startsWith("info")) {
... //format this field
}
}
return msg;
}
}
class GetOptException : Exception {
string infoOption; // this gets picked up by formatMsg
int internalData; // this is ignored
// No need to declare anything else except ctor to set
// the above fields.
}
This allows for a much cleaner, type-checked access to infoOption,
should the catching code know how to deal with GetOptException
specifically.
T
--
The day Microsoft makes something that doesn't suck is probably the day
they start making vacuum cleaners... -- Slashdotter
More information about the Digitalmars-d
mailing list