• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the cost of throwing and Exception vs the cost of returning null (or -1) ?  RSS feed

 
Myke Enriq
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lets say you are writing a function that returns an object.

If it can not return that object (for whatever reason) the function could return null. <- this is the first cost

If it can not return the object it can throw some exception (lets say it throws Exception e) <- this is the second cost


My question is how do we estimate how much bigger is the cost of the second approach compared to the cost of the first.

Please complete my thinking here:

- first approach:

Object f(parameters) -> returns null because for the given parameters it can not compute an object to return.

The cost of finding out that there is no object to compute vs actually calling f that returns null is smth like this:
- evaluate the "parameters"
- create copies of those parameters
- memorize program counter
- put the code of the function on the stack
- run that code on the stack with those copies
- return to the program counter

(I actually do not remember it clearly , please add to it if I am missing smth , this is of great value to begginers)

- second approach:

Object f(parameters) -> cost of running this function in a try{}catch() and catching an error compared to actually checking
first if that parameters can produce a result object and not calling the function :

- evaluate the "parameters"
- create copies of those parameters
- memorize program counter
- put the code of the function on the stack
- run that code on the stack with those copies
- the exception is thrown

<--- insert magic here , I have no idea what JVM does here ---->
(In a OS kernel module , when an Exception appears the OS creates a new namespace , saves the values of the registries , saves the file pointer , saves the pages
loaded into memory --- or smth like that , but it is not the JVM)

the JVM I guess looks for a handler for that exception (catch and finally are some sort of exception handlers), if none found it somehow ends current function and moves up to the parent function, in
the context of the parent function, and so on until the current Thread is ended.

I think the search for a handler has a cost , the realization that an exception is thrown has some cost as it generates a transfer of control.
<----------------------------------------------------------------------->

- return to the program counter




So my question is , can someone please make a diagram or a list of what happens inside <---> tags , meaning what does the JVM do when an exception is thrown.
Then please draw a conclusion on how much costlier throwing an exception is compared to returning null.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Throwing and then catching an exception is more costly than returning null (or another special value) and later detecting it. Exceptions are not designed to support normal flow of control, rather to handle, well, exceptional circumstances. So it is not a good idea to misuse exception instead of normal flow of control.

If the method can not return anything meaningful and has to tell somehow the required operation could not be performed, it should throw an exception. A constructor has no chance: if it does not throw an exception, the object will be considered as constructed and possibly a reference will be set to it. Many a method can return null and thus signalling it could not return an appropriate value. However there is no indication then on the reason of the failure.

Whether to throw an exception should depend on design considerations.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Myke,

Although not really an answer to your question, I think Ivan's response is really the best you can get - especially in the Beginning Java forum. The details you are talking about are the internal details of the JVM. They are really only important and interesting if you want to implement your own run time. The takeaway should be:
1) The choice between throwing an exception or returning a 'failed' response like null or -1 is a design decision, and not a performance issue. If being unable to generate a proper response is a normal situation which the caller should be able to detect and handle, then you should return null. If being unable to generate a proper response is exception, caused by an error or special circumstance that is not part of the normal control then you should throw an exception, regardless of the cost.*

2) It is more costly to throw an exception. The cost likely varies from VM to VM, but you could probably observe it by writing a simple program that loops through a method which does a fixed amount of work and then returns null, and a different method which does the same work but throws an exception at the end (which you then catch). Time 1000 (or ten thousand, or a hundred thousand....) iterations of each and calculate the average time for each method. The difference is the cost.



*edit--
And if the cost of throwing the exception is meaningful in the efficiency of your application, then it must happen often, and therefor be part of the normal control. If it were truly exceptional the performance cost should not really play into how well your application runs.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came came across this while working with JDOM.

JDOM: FAQ

When using an IDE debugger why do I see a strange ArrayIndexOutOfBoundsException?

Some parsers (Xerces included) use this exception as part of their standard operating procedure, internally throwing and catching the exception. No code outside the library is meant see it. However, IDE debuggers are often configured to report any time this exception is thrown, and thus they expose the exception. It can be safely ignored.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Myke Enriq wrote:Lets say you are writing a function that returns an object.

If it can not return that object (for whatever reason) the function could return null. <- this is the first cost
If it can not return the object it can throw some exception (lets say it throws Exception e) <- this is the second cost

My question is how do we estimate how much bigger is the cost of the second approach compared to the cost of the first.

I think you've already been given great advice. However, there may be a third alternative, which is often overlooked:
Return a "null" (or empty) OBJECT.

For example, if your method needs to return an array or collection of some sort, return one with 0 elements.

In other cases, you may be able to set up a "NULL" object (very likely a public constant) that has a fully documented behaviour.

Personally, I hate nulls; and I try to avoid them whenever I can.

Winston

PS: Cost (at least "efficiency" cost) should rarely be the deciding factor when determining a "best" approach.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!