Don’t raise exceptions for every little thing
by ricardoz on Apr.10, 2008, under Performance, Tips
Just in case you didn’t know, raising an exception makes the JVM do a lot of dirty work breaking execution flow and stuff. For example, try the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class MainExceptions { public static void main(String args[]){ int loops = 10000000; long timeStamp = System.currentTimeMillis(); for(int i=0; i<loops; i++){ try { doWithException(); }catch (Exception e){} } long totalTime = System.currentTimeMillis()-timeStamp; System.out.println(loops + " iterations with an exception thrown: " + totalTime + "ms"); timeStamp = System.currentTimeMillis(); for(int i=0; i<loops; i++){ doWithoutException(); } totalTime = System.currentTimeMillis()-timeStamp; System.out.println(loops + " iterations without an exception thrown: " + totalTime + "ms"); } private static void doWithException() throws Exception{ throw new Exception("Here it goes"); } private static int doWithoutException() { return -1; } } |
In my PC the results are:
10000000 iterations with an exception thrown: 11594ms 10000000 iterations without an exception thrown: 16ms
So does this mean you shouldn’t use exceptions? Not at all!! Exceptions are an exceptional tool in Java, just use them when something not expected happens in your code. For example if you can’t connect to a database you should throw an exception! But for expected code flows, just stick to returning the appropriate value.