Get the App
SLTechnology News&Howtos  ›  Development  › 

Why should exceptions be used cautiously in Java

Shulou Source: shulou.com Published: 2022-06-01 06:02:26 11月02日 Update

This article is about why exceptions need to be used with caution in Java. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Use anomalies with caution

In Java software development, try-catch is often used for error trapping, but try-catch statements are very bad for system performance. Although the loss of performance can not be detected in a try-catch, once try-catch is applied to the loop, it will bring great harm to the system performance.

The following is an example of applying try-catch to a for loop

Public void test () {int a = 0; for (int I = 0; I < 1000000; iTunes +) {try {a = a + 1; System.out.println (I);} catch (Exception e) {e.printStackTrace () }

The running time of this code is 27211 ms. If you move try-catch to extracorporeal circulation, you can improve system performance, as shown in the following code

Public void test () {int a = 0; try {for (int I = 0; I < 1000000; iTunes +) {a = a + 1; System.out.println (I);}} catch (Exception e) {e.printStackTrace ();}}

It takes 15647 ms to run. The influence of tyr-catch on system performance can be seen.

Thank you for reading! This is the end of this article on why you need to be cautious in using exceptions in Java. I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Performance system loop code content more article application run good practical bad medium loop body loss article time see knowledge example Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Xiaomi Shulou Tech Info MariaDB Huawei