Java: how to correctly use exceptions

Source: Internet
Author: User

Java: how to correctly use exceptions
Overview:

The exception mechanism in Java is a good thing. However, good things must be correctly used, otherwise it will make us mistakenly understand it. It will be incorrectly used if it is incorrectly recognized. This becomes a vicious circle. This is not what we are willing to see. Don't think we can use exceptions very well. Let's explain some of the problems below. Some of these problems come from 《Valid JavaIn this book, some of them come from my usual development process.

1. Whether it is throw or try-catch

This is a problem that people who are new to programming and development often face but choose badly.

Because the project we developed is not as easy as writing a Demo, there may be many hierarchies here. In which layer should we use the try-catch exception or throw the exception to the previous layer? Here, we first need to know one thing, that is, what happens to try-catch and throw?

Try-catch:Capture an exception and stopTry Block. And no exception will be thrown up.

Throw:When throw is used to throw an exception, the current execution block (method) ends subsequent execution. It is equivalent to a return operation, and ensures that the exception can be caught and processed by the upper layer during the call.

Demo example:

 

public class ExceptionClient {    public static void main(String[] args) {        ExceptionClient client = new ExceptionClient();                client.showInfo();    }        private void showInfo() {        try {            System.out.println("first info");            testException();            System.out.println("second info");        } catch (Exception e) {            System.err.println(e);        }                System.out.println("outside info");    }        private void testException() throws AException {        boolean f = true;        if (f) {            throw new AException("AException");        }                System.out.println("f is false.");    }}
According to the above analysis of try-catch and throw, we can know that the second sentence in the try block of the showInfo method is not printed, and the last sentence of the testException method is not printed. The result is as follows:

 

Figure-1 try-catch Test Result

 

2. Whether the exception is checked or not checked

First, we need to know what are checked exceptions and non-checked exceptions. Because the current IDE is very intelligent, when we use the checked exception without the try-catch exception, the IDE will give an error message. As follows:

Figure-2 IDE check for checked exceptions

The exception is not recognized by the IDE. Another point is that the IDE will detect checked exceptions. Therefore, if we forcibly run this code here, it cannot be compiled, but it will not.

The differences between checked exceptions and non-checked exceptions are described. Now let's talk about how to create these different exceptions.

When we want to write A custom checked Exception A. java, the class of A needs to inheritExceptionB. java is inherited.RuntimeException.

The exception will be detected during use, and developers are forcibly restricted to try-catch. When a try-catch exception occurs, the developer can correct the exception and perform the previous operation (recovery) again ). In RuntimeException, there is no such restriction. Therefore, when we try to tell the caller that the current exception can be repaired and re-called is allowed, we will use the exception to be checked, when we think this is a program error, we need to use a non-inspected exception.

You may have some basic knowledge about when to use checked exceptions or non-checked exceptions. Then you may ask the following question: do we still have an Error) what is the difference between them? The differences between the two are listed below (click to view the reference source ):

Exception:
1. It can be controllable (checked) or unchecked ).
2. indicate an error caused by a programmer.
3. It should be processed at the application level.
Error:
1. Always unchecked ).
2. It is often used to indicate system errors or low-level resource errors.
3. If possible, it should be captured at the system level.

 

3. Use exceptions only for incorrect Conditions

In this regard, we should first understand that Java consumes more system resources for exception checks than normal programs. If our program continuously performs exception checks, the overall performance of the program will be greatly affected. We can see this in a small example. As follows:

Assume that the List contains 10000000 elements. You can traverse the List in three ways:

First: perform an exception check for each situation

 

Private void call_1 (List
 
  
List) {long t = System. currentTimeMillis (); try {int index = 0; while (true) {list. get (index ++) ;}} catch (IndexOutOfBoundsException e) {LogUtils. printTimeUsed ("Exceptions not checked", t );}}
 
Second: only conduct exception checks for errors
Private void call_2 (List
  
   
List) {long t = System. currentTimeMillis (); t = System. currentTimeMillis (); int size = list. size (); int index = 0; while (true) {if (index> = size) {try {list. get (index ++);} catch (IndexOutOfBoundsException e) {LogUtils. printTimeUsed ("targeted check exception", t); break ;}} list. get (index ++ );}}
  
Third: normal loop Traversal
Private void call_3 (List
   
    
List) {long t = System. currentTimeMillis (); t = System. currentTimeMillis (); int size = list. size (); int index = 0; for (index = 0; index <size; index ++) {list. get (index ++);} LogUtils. printTimeUsed ("loop traversal", t );}
   

 

Test results:

Figure-3 traverse the List using different exception checking methods

From the above test results, we can see that the exception detection is not targeted (the blind check is abnormal), which is much lower than the targeted check for abnormal performance. Therefore, exercise caution when using exceptions. We need to avoid unnecessary exception checks to optimize our program code.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.