The Right Approach to Exceptions

deadalnix deadalnix at gmail.com
Mon Feb 20 10:50:54 PST 2012


Le 20/02/2012 19:42, H. S. Teoh a écrit :
> 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
>

This is bad design IMO. Exception are here to provide information about 
what is wrong. It has nothing to do with internationalisation whatsoever.


More information about the Digitalmars-d mailing list