Analysis of Java Exceptions

Source: Internet
Author: User
Tags finally block throwable

1. What is an exception

Poorly structured code does not work, which is the basic idea of Java.

The ideal time to find errors is at compile time. However, the compiler will not be able to find all the errors, and the remaining problems will need to be resolved when the program is run. This requires the error to be able to pass the appropriate information to the specific recipient in some way. The purpose of exception handling in Java is to simplify the generation of large, reliable programs by using a small amount of code, so that there are no unhandled errors in your application, and it also provides a significant benefit: reducing the complexity of error-handling code.

Unusual, according to the literal understanding, has the unexpected meaning. Put it at the code level to understand that it prevents the current method or scope from continuing execution.

In Java, an exception is treated as an object, and its base class is throwable.

2. Exception types in Java

Java derives exception and error directly from Throwable. Where exception is a basic type that can be thrown, a exception type exception may be thrown in Java class libraries, methods, and runtime failures, and error indicates compile-time and system errors. The structure hierarchy of the exception class is as follows:

Typical runtimeexception include NullPointerException, indexoutofboundsexception, illegalargumentexception, etc. ; non-runtimeexception including IOException, classnotfoundexception, etc.

In accordance with the compiler check method, the exception can be divided into check-type exception (checkedexception) and non-check-type exception (uncheckedexception). Error and RuntimeException are called uncheckedexception, because the compiler does not check whether the method handles or throws the two types of exceptions, so this type of exception during compilation does not cause an error. By default, the virtual machine provides the processing mode. In addition to the two types of exceptions, error and runtimeexception, other exceptions are called checked exceptions.

3, Java How to handle exception 3.1 Try-catch, try-finally, try-catch-finally

For an checked type exception, we either handle it or throw it at the method header using throws.

 Public Static void throws ioexception{    new File ("C:/test.txt");     if (! file.exists ()) {            file.createnewfile ();    }}
 Public Static void Main (string[] args) {    try  {        createFile ();     Catch (IOException ex) {        //  handle exceptionhere    }}

A few things to note about catch:

1), the exception type of the parameter must be the Throwable class or its subclass.

2), from the top down of the catch statement, its parameter types must follow from the subclass to the parent class order, because once a type is matched, the subsequent catch is ignored. For example, IOException must be placed in front of exception, or the compiler will error.

3), can have one or more catch statements, even if there is a finally statement, there can be no catch statement, such as try-finally.

To capture multiple exceptions, you can use multiple catch statements, and JDK7 later provides another way: multiple captures (Multi-Catch).

Try {    // Other codecatch (IOException |  SQLException ex) {    throw  ex;  }  

4), do not ignore exceptions. An empty catch block causes the exception to not achieve its intended purpose, unless, for example, when FileInputStream is turned off, because you have not changed the state of the file, you do not have to perform any recovery actions, and you have read the required information from the file, so you do not have to terminate the operation in progress.

Some points to note about the finally:

1), finally, the code is always executed, unless the virtual machine exits (System.exit (1)) when executing a try or catch statement.

2), finally block can do some resources cleanup work, such as closing files, closing cursors and other operations.

3), finally block is not required.

In addition, if the return statement is executed in the try and finally blocks, the return value in finally will be returned.

3.2 Abnormal chain

Often want to throw another exception after catching an exception, and want to save the original exception information, this is the exception chain. After JDK1.4, the Throwable subclass can accept a cause object as a parameter in the constructor, representing the original exception, passing the original exception to the new exception, so that if a new exception is created and thrown at the current location, the exception chain can be traced to where the exception first occurred.

But in Throwable subclasses, only error, Exception, runtimeexception three classes of exception classes provide constructors with cause parameters, and other types of exceptions need to pass the Initcause () method. For example, the Customexception class is defined, and can be used like this:

New customexception (); Cmex.initcause (new  nullpointerexception); throw Cmex;

This way, customexception inherits from Exception or RuntimeException and is a custom exception.

In general, the role of custom exceptions is as follows:

1), convert the Check type exception to a non-checked exception.

2), it is advantageous to encapsulate the context information, define the exception code, and collect the Environment object in the case of exception, which facilitates the transmission of information.

4. Exception Usage Guide

1), catch the exception if you know how to handle it.

2), custom exception types to encapsulate all check-type exceptions.

3), the exception is caught at the boundary of the program. such as the service side of the corresponding client request, at the exit of the catch inside a possible exception, and unified throw a encapsulated exception to the client, so as not to expose the server sensitive information.

4), use exceptions only for exceptions. Do not habitually use Try-catch in all your code, as this can affect performance.

5), throws a relative exception to the abstract. This situation can be overwhelming if the exception thrown by the method is not significantly associated with the task it performs. To avoid this problem, higher-level implementations should capture lower-layer exceptions and throw exceptions that can be interpreted according to a high-level abstraction, known as Exception translation (exception translation), as follows:

Try {    // use lower-level abstractionto does our biddingcatch( Lowerlevelexception ex) {    thrownew  higherlevelexception (...);}

Another special anomaly translation is called an anomaly chain, which is described above. If the low-level exception is very helpful for debugging problems that result in a high layer exception, it is appropriate to use an exception chain. The high-level exception provides an access method (Throwable.getcause) to obtain the lower layer exception.

6), each method throws the exception to have the document description. Use the @throws tag of Javadoc to record the conditions that throw each exception. If a method may throw more than one exception, do not use one of these exception classes. If you do not declare a method "throws Exception" or "throws Throwable", this will not have any guidance information.

Reference:

Java exception and error surface question 10 Q 10 Answer

Get rid of Java's inspected exceptions?

Handling of Java Exceptions and errors (Error)

Java Exception handling and design

Analysis of Java Exceptions

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.