Are there are any performance cost by creating, throwing and catching exceptions in Java?
I am planing to add \'exception driven development\' into a larger project.
Null objects is something which may be of help to you. I was reading Martin Fowler's book "Refactoring" the other day and it describes using a specific object which acts in the place of returning a null, saving you from having to check for NULL all the time.
I won't try to explain it here as it is described very well in the book.
I like this style of coding as it makes it very clear about what is going on from the point of view of someone using your API. I sometimes even name API methods getMandatoryUser(String)
and getUserOrNull(String)
to distinguish between methods that will never return null
and those which can return null
.
Regarding performance unless you're writing a very latency critical piece of code the performance overhead will be negligable. However, it's worth mentioning there are some best practices when it comes to try / catch blocks. For example, I believe Effective Java advocates creating a try / catch block outside of a loop to avoid creating it on each iteration; e.g.
boolean done = false;
// Initialise loop counter here to avoid resetting it to 0 if an Exception is thrown.
int i=0;
// Outer loop: We only iterate here if an exception is thrown from the inner loop.
do {
// Set up try-catch block. Only done once unless an exception is thrown.
try {
// Inner loop: Does the actual work.
for (; i<1000000; ++i) {
// Exception potentially thrown here.
}
done = true;
} catch(Exception ex) {
...
}
} while (!done);