custom exception type

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Fri Oct 22 04:35:08 PDT 2010


On Fri, 22 Oct 2010 13:00:43 +0200, spir wrote:

> Hello,
> 
> Where can one find descriptions of Throwable, Error, & Exception? (I
> mean, how do you even know they exist?) I could finally guess the
> constructor must have a string parameter used for error output.

Well, they should be in the documentation for the 'object' module, but I 
see that they aren't.  Until that is fixed, you can check out the 
source.  Throwable starts at line 1210 here:

  http://www.dsource.org/projects/druntime/browser/trunk/src/object_.d

Exception and Error immediately follow it, but they don't really add 
anything to Throwable.


> Also, is it possible to implicitely reuse the superclass's constructor?
> I had to write:
> 
> class E : Exception {
>     this (string msg) {
>         super(msg) ;
>     }
> }
> 
> E.this performs nothing new. But without it, I get a compiler error:
>     trial.d(7): Error: constructor trial.E.this no match for implicit
>     super() call in constructor
> Isn't the constructor inherited like other attributes?

No.  With the exception of a no-argument constructor, which Throwable 
doesn't have, you have to call it explicitly with super(...).


> Finally, is it possible to customize the error message construction,
> using eg tostring? A big issue is that, currently, an exception's
> message is computed at construction time, even if the exception will
> never be thrown, or more ccommonly never be output -- because it is
> caught by a 'catch' clause. In some cases, constructing the message can
> be costly; some programming schemes may throw huge numbers of
> exceptions, all caught (or nearly all). Example: in a parsing library,
> pattern match methods throw an instance of MatchFailure when matching
> fails. When there is a pattern choice, there may be numerous failures
> for each success. MatchFailure is just a clean way of signaling this
> fact (*): each failure exception is caught at a higher level to allow
> trying the alternative patterns. Since error messages can be rather
> complicated, constructing them uselessly would multiply parsing time by
> a rather big factor (in my case, ~ X 30!). I guess tostring is the right
> feature for this: it would return the exception's textual form, ie the
> message. (For information, this is how Python works.) I tried to use it,
> but it seems to be simply ignored. What is the func/method that
> constructs the text of an exception, eg what is implicitely called by
> "writeln(e);"?

That would be toString(), not tostring().

-Lars


More information about the Digitalmars-d-learn mailing list