1

I would like to override fillInStackTrace as a performance improvement, since I won't be needing the stack trace for my Exception. What's the correct way to do this?

The first method calls super() in the constructor, and the second does not. Does this make a difference?

If I call super() in the constructor, will the overridden fillInStackTrace be called, or will the fillInStackTrace from the superclass be called? to

I believe both methods are correct (in which case calling super is preferable) but I want to be sure.

Method 1

public class MyException extends Exception {
    public MyException() {
        super();
    }

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }
}

Method 2

public class MyException extends Exception {
    public MyException() {}

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }
}
ktm5124
  • 11,861
  • 21
  • 74
  • 119
  • 5
    Exceptions are supposed to be used for *exceptional* behavior. If you throw exceptions so often that it's a performance issue, then your likely using [exceptions for control flow](https://softwareengineering.stackexchange.com/q/189222/202153), and you shouldn't be doing that. Instead of hacking the symptom, maybe it would be better to fix the cause. – Andreas Oct 29 '18 at 21:55
  • 1
    `super()` is always called at some point in the constructor chain (usually implicitly, like in your Method 2), because there might be private fields that need to be initialized, that your subclass can't know about. – Clockwork-Muse Oct 29 '18 at 21:57
  • Basically yes. Your override `fillInStackTrace` method will be called from a `Throwable` constructor, whichever one is used. In this case, the same constructor will be called, so your two versions mean *precisely* the same thing. – Stephen C Oct 29 '18 at 22:46

0 Answers0