Search code examples
javagarbage-collectionheap-memory

Is it better to keep exceptions in Java for effectively use a garbage collector?


I want to induce a garbage collector less. Is it better to use this code:

private MyException myException = new MyException();

public void frequentlyUsedMethod(){
  try{
    ...
  }catch(Exception e){
    throw myException;
  }
}

instead of this:

public void frequentlyUsedMethod(){
  try{
    ...
  }catch(Exception e){
    throw new MyException();
  }
}

If I understand correct in the first case we create MyException only once but in the second case we will clog our heap and induce garbage collector many times.


Solution

  • No! Use the usual, idiomatic way and throw a new exception every time. There's a couple of issues with your suggested approach:

    1. It throws away any reasonable stack trace, the most important thing to see when an exception gets thrown out of your program (or logged). The stack trace is filled upon Exception creation, not when it is thrown, so all your stack traces would be the same, noninformative, and you'll have no idea which method threw them:

      Exception in thread "main" your.package.MyException
      at your.YourClass.<clinit>(YourClass.java:6)
      
    2. The code gets slightly more unreadable for "performance" reasons. That's always a sure way to hell, don't do that unless you can prove your change makes a significant difference. It's very likely that the exception object will not live for very long - in that case it's very cheap to clean it up for the GC.

    By the way, if your method throws an exception so often that it would make a difference, you uprobably are doing something very wrong anyway.