The Right Approach to Exceptions

H. S. Teoh hsteoh at
Mon Feb 20 10:21:13 PST 2012

On Mon, Feb 20, 2012 at 12:02:21PM -0600, Andrei Alexandrescu wrote:
> On 2/20/12 11:28 AM, Jose Armando Garcia wrote:
> >This may not be D. Gettext says to solve it as follow:
> >
> >throw new Exception(gettext("Cool English message at
> >%s.").format(
> >
> >The gettext "compiler" goes through the code an generates all the
> >strings that need to be localized. The translation teams modifies
> >those string and you store them in file/map for that language. At
> >runtime the i18n library turns gettext(...) into a query into that
> >map and returns the actual localized string. There is a map for the
> >entire process.
> >
> >Localization can also be disable at compile time by making gettext a
> >template and generating a "noop" for that operation.
> So this moves formatting from the catch point to the throw point.
> That's fine, but it forces the formatting effort upfront even when the
> message is not actually used and leads to duplication because each
> call site would need to provide the message entirely. I think it's
> worth investigating formatting at the catch site.

Ah, I see what you're getting at. What about this then:

	class MyException : Exception {
		int info1;
		string info2;

		// class Exception would provide a default formatMsg()
		// that simply prints Exception.msg, perhaps also with
		// translation.
		override string formatMsg(LocaleInfo li) {
			return formatI18n(li, "...", info1, info2, ...);

This way, the catcher doesn't have to know anything about info1, info2,
..., unless it specifically wants to catch MyException and do error
recovery based on info1, info2, ... etc.. And the formatting isn't
actually done until it's needed. The thrower only sets info1, info2,
..., only when the catcher wants a human-readable message out of it, it
will call formatMsg().

> >I have been thinking of making a module for i18n model after gettext
> >but taking advantage of D's language features. Is there some interest
> >in this?
> Yah, this would be of interest.



I'm still trying to find a pun for "punishment"...

More information about the Digitalmars-d mailing list