The Right Approach to Exceptions

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Feb 20 13:21:56 PST 2012


On Mon, Feb 20, 2012 at 02:57:08PM -0600, Andrei Alexandrescu wrote:
> On 2/20/12 1:45 PM, Jonathan M Davis wrote:
> >On Monday, February 20, 2012 20:42:28 deadalnix wrote:
> >>Le 20/02/2012 20:27, Jonathan M Davis a écrit :
> >>>On Monday, February 20, 2012 11:15:08 H. S. Teoh wrote:
> >>>>That's why I proposed to use runtime reflection to scan the exception
> >>>>object for applicable fields. Then you get the best of both worlds: the
> >>>>message formatter doesn't need to know what the fields are, and you get
> >>>>full compile-time type checking for catching code that directly accesses
> >>>>the fields.
> >>>
> >>>That would certainly be better.
> >>>
> >>>- Jonathan M Davis
> >>
> >>This is way better than Variant[string], but unimplemented ATM.
> >
> >Yes, but you can use compile-time constructs to generate it. And as you
> >pointed out in another post, tupleof should do the trick. Regardless, the
> >point is that using reflection of some kind is a much better solution than
> >using variant.
> 
> Agreed. Ideally adding a sort of mixin to any class would enable it
> for advanced run-time information:
> 
> class DRoxException : Exception
> {
>     mixin(enableRTTI);
>     ... normal implementation ...
> }
[...]

Doesn't this need compiler/language support?

Barring that, a temporary workaround for lack of RTTI would be to have a
template that generates actual fields along with an index of fields via
mixins, something like this:

	// NOTE: not actual syntax
	template GenFormattingFields(T..., T fields) {
		...
	}

	class RoxorException : Exception
	{
		GenFormattingFields!(
			string, "filename",
			int, "line",
			int, "column"
		);

		int nonFormattingField;
		...
	}

The template would generate code along these lines:

	// Generated code (not actual syntax)
	class RoxorException : Exception
	{
		string filename;
		int line;
		int column;

		override Variant[string] getFormattingFields() {
			return [
				"filename": filename,
				"line": line,
				"column": column
			];
		}

		int nonFormattingField;
		...
	}

where getFormattingFields is a virtual function defined by Exception.
Then you can get the fields for formatting at runtime, *and* have static
type checking of direct accesses to RoxorException.filename, etc., at
compile-time.


T

-- 
Trying to define yourself is like trying to bite your own teeth. -- Alan Watts


More information about the Digitalmars-d mailing list