The Right Approach to Exceptions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Feb 20 10:47:17 PST 2012


On 2/20/12 12:42 PM, H. S. Teoh wrote:
> 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.

But this moves i18n code straight inside the exception, which Jonathan 
argues against. Separated concerns call for separated modules.

Sorry, I don't know what to write beyond the one line above!


Andrei




More information about the Digitalmars-d mailing list