Throw and catch an exception, or use instanceof?

exception, instanceof, java, performance, throws

Solution

I'd advise using `instanceof` as it will likely be faster. Throwing an exception is a complicated and expensive operation. JVMs are optimized to be fast in the case when exceptions don't happen. Exceptions should be exceptional.

Note that the `throw` technique probably won't compile as shown, if your exception type is a checked exception, the compiler will complain that you must catch that type or declare it as thrown (corresponding to an `else { ... }` clause if you use the `instanceof` technique), which might or might not be helpful, depending on how you want to handle exceptions that are not one of the specific sub-types.

Problem

I have an exception in a variable (not thrown). What's the best option? ``` Exception exception = someObj.getExcp(); try { throw exception; } catch (ExceptionExample1 e) { e.getSomeCustomViolations(); } catch (ExceptionExample2 e) { e.getSomeOtherCustomViolations(); } ``` or ``` Exception exception = someObj.getExcp(); if (exception instanceof ExceptionExample1) { exception.getSomeCustomViolations(); } else if (exception instanceof ExceptionExample2) { exception.getSomeOtherCustomViolations(); } ```

Original source

Related problems