6

I want to declare a custom exception class that takes a message and also does some custom tracing:

public MyException extends Exception{

    public MyException(String msg){
        MyTracing.trace(msg);
        this(msg);
    }
}

I couldn't make this work so I created a static factory method that first traces then calls my new MyException instead, I'm just building up familiarity with apex and wondered if anyone could tell me whether or not this can be done without a workaround?

7

Unfortunately, you cannot do this, because constructors cannot be overridden. As a workaround, I would suggest the following alternative:

public class MyException extends Exception {
    public MyException withMessage(String msg) {
        MyTracing.trace(msg);
        return this;
    }
}

This changes your invocation to:

throw new MyException().withMessage('Divide by zero makes me sad');

Or, you could just add another parameter to the mix. For example:

public class MyException extends Exception {
    public MyException(String msg, Boolean reserved) {
        this(msg);
        MyTracing.trace(msg);
    }
}
| improve this answer | |
  • 1
    Thanks for the info, Yes this is my static method: public class MyException extends Exception { public static MyException create(String msg) { MyTracing.trace(msg); return new MyException(msg); } } – Grokodile Jan 9 '14 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.