exception types & objects

Simen kjaeraas simen.kjaras at gmail.com
Tue Oct 19 05:52:20 PDT 2010


spir <denis.spir at gmail.com> wrote:

> Hello,
>
> The reference states:
>
> ThrowStatement:
> 	throw Expression ;
> Expression is evaluated and must be an Object reference. The Object  
> reference is thrown as an exception.
> 	throw new Exception("message");
>
> The example uses an Excpetion type, but the somewhat comment contradicts  
> it. Can one really use any kind of object as exception?

Absolutely. It is however heavily discouraged.


> How does D then handle it?

The way it does any other exception. You may catch it using
catch(Object o).


> I was expecting (from exp with other language) there to be a root Error  
> or Exception type implementating base exception mechanics and/or an  
> imposed interface to comply with (esp a kind of string method returning  
> what text to write out when the exception is not caught).
> How does this work, and how to use it concretely?

There is a base class Exception and Error, as well as the base interface
Throwable, which the aforementioned implement. Using this is more of a
convention than absolute necessity, but it is used all over Phobos and
druntime, and it is heavily discouraged not to use those as bases.

On a sidenote, one should usually only catch Exceptions, not Errors, as
the latter is supposed to be used for non-recoverable errors.

-- 
Simen


More information about the Digitalmars-d-learn mailing list