Custom Exception with a constructor that takes parameters

I’d like to extend Exception to create a custom exception class that takes several arguments in addition to the standard string message.

I’ve found examples showing basic inheritance (An Introduction to Exception Handling) and adding custom constructors (Extended Class Example).

public virtual class MyException extends Exception {
    public Double d;

    // Exception class constructor     
    MyException(string message, Double d) {
        // How can I pass 'message' to the base constructor?
        this.d = d;
    }
}

When using a custom exception similar to the example above calls to getMessage() return ‘Script-thrown exception’, which makes sense as message hasn’t been utilized yet.

How can I extend Exception and include a custom constructor such that Exception.getMessage() returns a string specified in the constructor?

Or more generally, how do I pass arguments from my custom constructor to the base constructor in Apex?

Answer

You can use this(message) in your constructor to call the base class constructor:

public virtual class MyException extends Exception
{
    public Decimal d;

    public MyException(String message, Decimal d)
    {
        this(message);
        this.d = d;
    }

    @isTest
    static void test()
    {
        try
        {
            throw new MyException('this is my message',3.1415);
        }
        catch(Exception e)
        {
            system.assertEquals('this is my message', e.getMessage());
            MyException me = (MyException) e;
            system.assertEquals('this is my message', me.getMessage());
            system.assertEquals(3.1415, me.d);
        }
    }
}

However, I would have expected the System Exception class to behave like a virtual Apex class (and therefore be able to use super(message) in this situation).

Attribution
Source : Link , Question Author : Daniel Ballinger , Answer Author : Stephen Willcock

Leave a Comment