override toString of Exception

Ali Çehreli acehreli at yahoo.com
Sun Oct 21 09:40:47 PDT 2012


On 10/20/2012 09:42 AM, David wrote:
> class BraLaException : Exception {
> this(string s, string f=__FILE__, size_t l=__LINE__) {
> super(s, f, l);
> }
>
> override string toString() {
> return "bar";
> }
> }
>
>
> when throwing this exception, I still get the stacktrace and not "bar",
> is it possible to change that behaviour?

The backtrace is not printed if the exception is caught:

class MyException : Exception
{
     string s;

     this(string s, string f=__FILE__, size_t l=__LINE__) {
         super("bar", f, l);
         this.s = s;
     }

     override string toString() const
     {
         return s;
     }
}

void main()
{
     try {
         throw new MyException("bar");

     } catch (Exception e) {
         assert(e.toString() == "bar");
     }
}

This behavior makes sense to me because printing the backtrace should 
concern the application, not the exception itself. If the application 
does not want the backtrace printed, it can handle all of the exceptions.

Ali


More information about the Digitalmars-d-learn mailing list