The difference between the checked exception and the unchecked exception in Java is described in detail.

Source: Internet
Author: User

The difference between the checked exception and the unchecked exception in Java is described in detail.

(1) Java exception hierarchy

To understand the differences between checked Exception and unchecked Exception in Java, Let's first look at the Java Exception hierarchy.

 

This is a simplified Java Exception hierarchy. It should be noted that all classes are inherited from Throwable, And the next layer is divided into two structures: Error and Exception. The Error class levels describe the internal errors and resource depletion errors of the Java runtime system. In addition to reporting these errors to users and trying to prevent program termination, there are other solutions to this problem.

(2) differences between unchecked and checked exceptions

With the above understanding, let's look at what is a checked exception and what is an unchecked exception. In fact, the Java language specification is very simple for these two definitions,The exception derived from Error or RuntimeException is called an unchecked exception. All other exceptions become checked exceptions.. Although this definition is very simple, RuntimeException is a very confusing concept. It seems that all our exceptions are running. The explanation of the Ru ntimeException exception in objective Java is not so satisfactory,

Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)

However, we can simply extend this sentence, that is,If RuntimeException occurs, it must be a programmer's own problem.For example, the array subscript is out of bounds and the access NULL pointer is abnormal. As long as you pay attention to these exceptions, they can be avoided in the encoding phase. If you still think that these two concepts are difficult to distinguish, the "most violent" method is to back the common RuntimeException, which saves a lot of time for judgment.

(3) Why should we differentiate unchecked and checked exceptions?

The reason is actually very simple. The compiler will check whether you provide an exception handling mechanism for all checked exceptions. For example, we use Class. when forName () is used to find the class object of a given string, compilation fails if exception handling is not provided for this method.

(4) what exceptions should we declare?

As we mentioned earlier, RuntimeException is an error that can be avoided during the programing process. Do we not need to throw these exceptions? In principle, this is the case, but the Java specification does not limit this. It just seems that the exception that throws an array out of bounds does not have much practical significance, on the contrary, it may cause some performance losses. So how should we design and throw exceptions? Note that throws exceptions must be declared in the following two cases:

Call a checked exception method, such as IOException. As for the cause, we have discussed earlier. If all checked exceptions are thrown, compilation fails. When an error is found during the program running, throw an exception using the throw statement. For unchecked exceptions, there are only two main cases: Runtime Exception and uncontrollable. These also need to declare exceptions.

The following examples illustrate the awkward things mentioned in note 2:

First, define a basic Exception class GenericException, which inherits from Exception.

package check_unchecked_exceptions;public class GenericException extends Exception{  /**   *    */  private static final long serialVersionUID = 2778045265121433720L;    public GenericException(){      }    public GenericException(String msg){    super(msg);  }}

The following defines a test class VerifyException.

package check_unchecked_exceptions;public class VerifyException {  public void first() throws GenericException {    throw new GenericException("checked exception");  }    public void second(String msg){    if(msg == null){      throw new NullPointerException("unchecked exception");    }  }    public void third() throws GenericException{    first();  }    public static void main(String[] args) {    VerifyException ve = new VerifyException();        try {      ve.first();    } catch (GenericException e) {      e.printStackTrace();    }    ve.second(null);  }}

After running, you can get the following information on the eclipse console:

Check_unchecked_exceptions.GenericException: checked exception
At check_unchecked_exceptions.VerifyException.first (VerifyException. java: 6)
At check_unchecked_exceptions.VerifyException.main (VerifyException. java: 23)
Exception in thread "main" java. lang. NullPointerException: unchecked exception
At check_unchecked_exceptions.VerifyException.second (VerifyException. java: 11)
At check_unchecked_exceptions.VerifyException.main (VerifyException. java: 29)

In the above example, combined with the concepts of checked and unchecked, we can see that the parent class of Exception is of the checked type, but its subclass RuntimeException (subclass NullPointerException) is unchecked.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.