DEV Community


Discussion on: Is there a price to pay for using exceptions?

nickhristov profile image
Nick Hristov

First of all the way you think of exceptions is somewhat off. You should think of exceptions as precisely what they are: an exception to the normal flow of a program and a useful way of rolling many layers of stack.

Their value becomes apparent the moment you try to use a language that does not have them. To illustrate: you have written a flow in that language that has no exceptions. You are writing modular code and have a decent set of small functions. As you write a function that's three calls deep into the main function, you realize that there is an error condition that has to terminate the flow. So your function now needs to return a status, and error string, and the original intended value. Of course, the calling function has to have the code to handle the error status and propagate it up. It itself needs to have an error status an error message and the actual result as a result tuple. On top of this, your innermost function gets called from multiple places, and when it errors out you have no idea where the call came from (you have no stack traces, just error messages). This quickly becomes a giant PITA, and you decide that exceptions can be pretty handy.

Second, EmployeeException should not exist. Use IllegalArgumentException instead, it's built for that. For nulls, throw NPEs.

Third, use checked exceptions only when you want to force the caller to handle the exception. In most cases the use of checked exceptions is unnecessary. Timeouts are a good example for checked exceptions. Interrupted threads as well.

Fourth, don't worry about the performance of exceptions. Use them only when you truly need them (not for flow control), most of the other code you write will be a much bigger performance issue rather than how fast is JVM native code.

Fifth, this is not how you do micro-benchmarks. If you want to test the performance of exceptions then test just for that. Your code also allocates memory and prints. While memory allocs are fast, under high throughput you can exhaust your allocation pools and then go kicks in. That will totally mess up your numbers. You are also not accounting for JIT and for CPU pipelining and branch prediction. In short, micro-benchmarking is a bit of a dark art and requires a lot of time and careful set up to get right.