Home >Java >javaTutorial >Why you need to use exceptions with caution in Java
Use exceptions with caution
In Java software development, try-catch is often used to capture errors. However, the try-catch statement is very bad for system performance. Although the performance loss caused by try-catch cannot be detected in a try-catch, once try-catch is applied to a loop, it will cause great damage to system performance.
The following is an example of applying try-catch inside a for loop
public void test() { int a = 0; for (int i = 0; i < 1000000; i++) { try { a = a + 1; System.out.println(i); } catch (Exception e) { e.printStackTrace(); } } }
The running time of this code is 27211 ms. If try-catch is moved outside the loop, system performance can be improved. The following code
public void test() { int a = 0; try { for (int i = 0; i < 1000000; i++) { a = a + 1; System.out.println(i); } } catch (Exception e) { e.printStackTrace(); } }
takes 15647 ms to run. It can be seen the impact of tyr-catch on system performance.
The above is the detailed content of Why you need to use exceptions with caution in Java. For more information, please follow other related articles on the PHP Chinese website!