Java size of an Exception in memory

exception, java, memory, nullpointerexception

Solution

Does anyone know how much memory an Exception occupies once it is created and thrown?

That would depend entirely on the exception. Like any other object, it contains variable amount of data; the `String` message could be 4MB if someone did something silly:

Exception e = 
    new Exception(new String("Some gigantic message ... lalalalalalalalla"));

(Edit: ok, this is somewhat misleading; the exception contains a reference to a `String` and reference values are a fixed size, but the `String` itself might only be referenced by the exception - I changed it to be a non-literal to explicitly show it could be something that is collectible. A custom exception could hold anything though, it's an object like any other. In addition, it depends how far it has been thrown, since it holds the stack trace inside of it. There's a good Q/A here on SO; In java, what is the best way to determine the size of an object that covers this. )

And how exceptions are being garbage collected?

Just as any other object is. The Exception is thrown up the call stack and one of two things happen:

1) You catch it, and it's assigned to a variable in the catch block:

catch (Exception e) {

`e` now holds the one and only reference to the exception. When no more references to it exist (i.e. it either falls out of scope at the bottom of the catch block, or the object you pass it to gets collected, etc), it will get collected.

2) You don't catch it and it hits the top of the call stack for the current thread. At that point the exception falls out of scope so it will be collected, and the thread is of course halted.

** To be completely pedantic when I say "will get collected" I mean eventually as when an object in Java has no more references to it it's it's eligible for collection, and the GC deals with it.

Problem

Does anyone know how much memory an Exception occupies once it is created and thrown? For example, `NullPointerException`. And how exceptions are being garbage collected?

Original source

Related problems