Home > Java > javaTutorial > Why you need to use exceptions with caution in Java

Why you need to use exceptions with caution in Java

王林
Release: 2023-04-20 10:28:06
forward
1032 people have browsed it

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();             }         }     }
Copy after login

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();         }     }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template