views:

191

answers:

6

This may be a strange question, but do 'try-catch' blocks add any more to memory in a server environment than just running a particular block of code. For example, if I do a print stack trace, does the JVM hold on to more information. Or is more information retained on the heap?

try {
  ... do something()
} catch(Exception e) {
 e.printStackTrace();
}


... do something()
A: 

The stack trace is built when the exception is created. Printing the stack trace doesn't do anything more memory intensive than printing anything else.

The try/catch block might have some performance overhead, but not in the form of increased memory requirements.

Outlaw Programmer
+2  A: 

The exception will hae a reference to the stack trace. printStackTrace will allocate more memory as it formats that stack trace into something pretty.

The try catch block will likely result in a largely static code/data segment but not in run time memory allocations

hacken
+1  A: 

The important here is as soon the exception variable 'e' is no longer reachable (ie, out of scope) it becomes eligible for memory collection.

Miguel Ping
A: 

For the most part, don't worry about memory/performance when exceptions happen. If you have an exception that is a common code path then that suggest you are misusing exceptions.

If your question is more for academic purposes, then I don't know the full extent of what is going on there in terms of heap/memory space. However, Joshua Bloch in "Effective Java" mentions that the catch block of the try catch block is often relatively unoptimized by most JVM implementations.

James McMahon
A: 

Technically the answer to your question is probably no. There are lots of reasons to avoid throwing Exceptions whenever possible, but memory isn't really a concern.

The real reason to only throw Exceptions for truly exceptional conditions is that it's SLOW. Generating an exception involves carefully examining the stack. It's not a fast operation at all. If you're doing it as part of your regularly flow of execution, it will noticeably affect your speed. I once wrote a logging system that I thought was extremely clever because it automatically figured out which class had invoked it by generating an Exception and examining the stack in that manner. Eventually I had to go back and take that part out because it was noticeably slowing everything else down.

CaptainAwesomePants
A: 

While not directly related to memory consumption, there was a thread here a while back discussing How slow are the Java exceptions? It is worth a look, in my opinion.

I also had this link in my bookmarks. As far as I can recall, it gave an example of speed up possible when stack trace generation is skipped on exception throw, but the site seems down now.

javashlook