Thread overview
Tutorial on writing Exceptions
Jul 05, 2004
Gold Dragon
Jul 06, 2004
Arcane Jill
Jul 06, 2004
Sam McCall
July 05, 2004
Can I have a clear tutorial on how to create exceptions. You throw the exception of course and I guess inherit from Error. Which module is that and exactly how does D want you program the throwing?
July 06, 2004
In article <cccfah$700$1@digitaldaemon.com>, Gold Dragon says...
>
>Can I have a clear tutorial on how to create exceptions. You throw the exception of course and I guess inherit from Error. Which module is that and exactly how does D want you program the throwing?

If I'm in a hurry, I might just do:

#    throw new Error("Bad parameter 3 to function f()");

If I'm writing something a bit more enduring, I might first define:

#    class MyError : Error
#    {
#        this(char[] s)
#        {
#            super(s);
#        }
#    }

and then I can do:

#    throw new MyError("Cannot divide by zero");

which is pretty similar, all told, but of course a MyError can be caught in isolation from other kinds of errors.

There's a localization problem, of course. If you don't speak English, the display of my error message won't help you - but adding localization to error handling may be going a wee bit too over-the-top.

But there is also such a thing as an exception with is /programmatically/ useful - that is, useful to software, not just an error message to humans. You can stuff information into a class derived from Error or Exception, such as the exact parameters which caused things to go wrong, the offset into a stream gone bad, etc. This is only useful if you catch the exception, but it's something you might want to do if you thing there's a chance that some calling function MIGHT want catch it and examine it.

(Others please chime in here - I'm not an expert on this, and D's exception base classes are not that clear to me).

Arcane Jill


July 06, 2004
If you do want to catch a MyError, I think the convention is to subclass it from Exception, with Errors being uncaught in almost all cases.

Arcane Jill wrote:
> There's a localization problem, of course. If you don't speak English, the
> display of my error message won't help you - but adding localization to error
> handling may be going a wee bit too over-the-top.
If you were writing a big, localized app, I guess you would use your own exception base class that looked up message format strings from a table or something. Doesn't seem to be a need for it to be in the base classes, since a lot of exceptions will be invisible (or at least opaque) to the user.

Sam