[phobos] Printing exceptions

Andrei Alexandrescu andrei at erdani.com
Wed Apr 7 11:39:20 PDT 2010


This seems to be an instance of the problem NVI is supposed to solve: 
the interface for users should not be the same as the interface for 
customization.

In an NVI approach, toString would be final and there would be an 
overridable toStringImpl that users can tweak. Then toString would call 
toStringImpl and decorate it with stack trace info etc.

Anyway, since toString is already overridable, I suggest you just add a 
detailedReason() function that formats and returns a string including 
whatever toString() returns, then also file and line info and stack 
trace. If an exception leaves main(), print detailedReason(), not 
toString().


Andrei

On 04/07/2010 01:09 PM, Sean Kelly wrote:
> On Apr 7, 2010, at 8:53 AM, Robert Clipsham wrote:
>
>> On 07/04/10 16:29, Sean Kelly wrote:
>>> The runtime can do one of two things: print exceptions according to a standard format and inject the msg field in the proper place or it can call toString.  Which should be done?  I prefer the former because it makes for a standard presentation and doesn't risk allocating memory needlessly, but I can see how people might do fancy stuff in toString that they expect to be used instead.  This came up because I'm adding a default stack trace handler, and the current behavior prints the stack trace twice, so something needs to change.
>>
>> I think the better option would be to print them in the standard format, at least by default. You could always include several trace handlers to allow the user to effortlessly pick the handler they want, rather than everyone implementing their own for when they want to use toString.
>
> My worry is that someone will do something fancy in their toString override and expect it to print if the exception escapes main().  The default behavior is basically to print "file:line: msg" which sidesteps any custom code in toString completely.  The current code is actually a bit weird and uses the custom format if the file string is non-null and calls toString otherwise, but that seems like it's even less predictable than simply always using a custom or the toString format.  I also don't see any easy way to provide a default formatter, since ranges are defined in Phobos and not druntime (ie. you couldn't have Exception.outputTo(Range)).
>
> I've personally never liked toString, but since it exists it seems like the only reasonable thing to do is always call it.
> _______________________________________________
> phobos mailing list
> phobos at puremagic.com
> http://lists.puremagic.com/mailman/listinfo/phobos


More information about the phobos mailing list