Java Exception handling methods

Source: Internet
Author: User
Tags class definition constructor exception handling finally block throwable

Exception: an Exception occurs during the running of the program.

1. Exception handling mechanism for Java exceptions

Early cases:

The programming languages used in the early stage did not provide special exception handling functions. The programmers can only use conditional statements to judge various possible errors, to capture and handle specific exceptions. In this way, if... Else statement. The code block that originally needed to complete the corresponding function is very small, but the code is very bloated with such conditional statements for exception handling, so that the code's readability and maintainability are reduced, in addition, unexpected exceptions may be missed.

Java:

Java provides a powerful exception handling mechanism for the above situation, which can be said to bring the gospel to programmers. Java's exception handling mechanism can easily monitor program blocks that may encounter exceptions in programs, all exception handling codes are concentrated somewhere in the program so that the program code that completes normal functions is separated from the program code that performs exception handling. The exception handling mechanism reduces the workload of programmers, enhances the flexibility of exception handling, and greatly improves the readability and maintainability of programs.

In the Java processing mechanism, some classes are introduced to describe and handle exceptions. Each exception class reflects a class of running errors, the class definition contains information about the class exception and the methods for handling the exception. When an exception occurs during the process of running the program, the system generates an exception object corresponding to the object and submits it to the corresponding mechanism in the system for processing, to avoid system crashes or other harmful results, and ensure the security of program running.

2. Definition of Java exception classes

In Java, exceptions are divided into Error and Exception ).

Error: The program itself is invalid, which is often caused by code problems. In addition, programmers can carefully check the program updates to minimize the number of such errors. Theoretically, these situations can be avoided.

Exception: Another "unusual" error. Such errors are usually unpredictable. Common exceptions include insufficient memory and missing files.

The Throwable class derives two subclasses: Exception and Error.

The Error class describes an internal Error, which is retained by the system. The program cannot throw this type of object. The Error class object cannot be captured or recovered. When an Error occurs, the system notifies the user and terminates the program;

The Exception class is used by the program. All Java Exception classes are subclasses of the Exception class in the system Library.

 

Inheritance relationship:

 

 

The Throwable class is the parent class of all exception classes and implements the Serializable interface. Throwable has two important subclasses: Exception and Error, which indicate exceptions and errors respectively. Exceptions generally indicate problems that can be detected, recoverable, or avoided in encoding. They are generally mild errors. Errors usually indicate serious problems and are not related to code execution in most cases, for example, OutOfMemoryError.

The checked exception indicates that the caller is expected to take some recovery measures when the exception occurs, or spread the exception. For example, our taogoods exception is a checked exception. When a method throws a checked exception, it means to inform the caller that to call this method, you must capture the exception I throw. Of course, the caller can ignore this exception after capturing it, but this is usually not a good method. At least a log should be printed.

Runtime exceptions and errors are uncheckable and can be thrown. They are in the same behavior: they do not need to be captured. This is because when our program throws these two types of structures, it usually indicates that the error cannot be recovered. It is harmful to continue to execute, such as IndexOutOfBoundsException, ArithmeticException, and OutOfMemoryError. IndexOutOfBoundsException indicates that the array or string is out of the index range, ArithmeticException indicates that the operation is abnormal (for example, the denominator is 0), and OutOfMemoryError indicates that the JVM does not have enough memory to allocate. The first two exceptions both belong to RuntimeException, indicating that this exception is a programming error. We should avoid this problem in our program, instead of solving it by capturing. The latter is an error that we cannot solve through Encoding. This error is usually a serious problem, generally due to a JVM error.

2 Java Exception handling principles

2.1 do not ignore exceptions

This is the most basic principle for exception handling. When an exception is thrown, it indicates a problem occurs somewhere in the program. Ignoring an exception may not achieve the expected results. We should handle exceptions in the program or continue to throw them. At least, we should include a statement that records the exception into the log for future analysis.

2.2 use as few exceptions as possible, and prioritize standard exceptions

Exception handling has certain overhead. Unless exceptions occur, do not apply exceptions to common control flows. For example, do not use exceptions to detect whether the array is out of bounds. As follows:

// Excerpt from objective Java

Try {

Int I = 0;

While (true)

Range [I ++]. climb ();

} Catch (ArrayIndexOutOfBoundsException e ){

}

Also, do not always rely on exceptions to solve the null pointer problem. We should determine whether the object is null before calling the method. Note that you need to determine whether all required objects are null. One problem I encountered previously was that only some of them are null, as shown in the following code:

If (baskItem. getStatus ()! = Null & baskItem. getStatus (). getStatus ()! = Status. TOP. getStatus ())

The baskItem is null during running. Of course, this situation is rare, but in some extreme situations, it will still happen.

When exceptions are used, standard exceptions rather than custom exceptions are preferred, which makes your code more readable (because standard exceptions are familiar to everyone) and reduces the number of exception classes.

Common standard exceptions include:

IllegalArgumentException. This exception indicates that the caller has passed an inappropriate parameter. We can throw this exception when detecting that the parameter is incorrect, or return a null value or false to end the method.

NullPointerException, which is the most familiar exception. If the caller passes a null value in a parameter that does not allow null values, the habit is to throw the NullPointerException exception.

IndexOutOfBoundsException: if the caller passes an out-of-bounds value in the parameter of a sequence, the IndexOutOfBoundsException exception should be thrown. For example, you can access an array element that exceeds the array's bottom mark.

ConcurrentModificationException. This exception is designed in the java. util package to indicate that a single-threaded object is being modified concurrently.

UnsupportedOperationException. This exception indicates that the current object does not support the requested operation. For example, if the implementation class does not implement the interface definition method, this exception will be thrown.

NumberFormatException. This exception indicates that the data format is incorrect, and an ArithmeticException indicates an arithmetic exception. For example, 0 is passed as the divisor in the division operation.

In addition, the DAOException we used is abnormal, indicating a problem occurred while accessing the database.

2.3 all exceptions thrown by each method must be documented.

It is also necessary not only to create a document for each method, but also to establish a complete document for the exceptions thrown by each method.

Each checked exception must always be declared separately, and the @ throws mark of Javadoc should be used to accurately record the conditions for generating each exception. As follows:

/**

* Create a POIFSFileSystem from an InputStream

*

* @ ParamStream the InputStream from which to read the data

*

* @ ExceptionIOException on errors reading, or on invalid data

*/

PublicPOIFSFileSystem (FinalInputStream stream)ThrowsIOException;

(Note: @ ecxeption is used before @ throws)

For unchecked exceptions, you only need to use the @ throws tag to record possible exceptions and conditions. However, do not include the exception in the Declaration of the method using the throws keyword. This is because exceptions declared using the throws keyword must be captured in the caller's code, while those not checked do not need to be captured by the caller.

2.4 Record the useful information of the caught exception

When an exception occurs, we usually check the cause of the exception to troubleshoot the problem. Therefore, it is helpful to include as much details as possible to solve the problem. Fortunately, general exceptions record the class name, method name, and location where exceptions occur, as well as a large amount of stack information.

In fact, this information alone cannot fully meet our needs. Sometimes, we can identify an error when operating the database through an exception, but we are not sure whether our SQL statement is wrong or we do not have operation permissions, or other errors occur during database operations. At this time, we may want to see the executed SQL statement or other intermediate states. It is also necessary to record this information. There are two ways to achieve this: one is to record the information after an exception is captured, and the other is to introduce this information in the constructor of the custom exception class. For example, we can define the following constructor in the IndexOutOfBoundsException exception.

PublicIndexOutOfBoundsException (IntLowerBound,IntUpperBound,

IntIndex ){

Super("Lower bound:" + lowerBound + ", Upper bound:" +

UpperBound + ", Index:" + index );

This. LowerBound = lowerBound;

This. UpperBound = upperBound;

This. Index = index;

}

The above code is taken from objective Java. Although JDK does not do this, Joshua Bloch strongly recommends this practice.

In fact, SQLException contains detailed information records. You can check the source code of SQLException and find that it has the following constructor:

PublicSQLException (String reason, String sqlState,IntVendorCode, Throwable cause)

This Constructor records the cause of the exception in detail. Reason indicates the cause of the exception. sqlState indicates XOPEN or SQL: 2003 (a standard) code about exception classification. vendorCode indicates the specific exception code of the database.

With the above information, we can use the getSQLState () and getErrorCode () methods in SQLException to obtain more precise exception information.

2.5 strive to keep failures Atomic

The atomicity of failure means that the failed method call should keep the object in the state before the call. From objective Java

This may sound abstract, but it is easy to understand. Try to think about a situation where, after we capture an exception, we will not terminate our code and continue to execute, but try to recover from this exception. However, the value of an object is changed in the exception. In this way, what we get in the next operation may be an unexpected value. For example, if we want to share statistics for a certain operation and use the following code, we may fail to get the sharing, but the counter is incremented by 1, obviously it is not the expected result.

IntCount = 0;

For(LongBaskItemId: arraylist ){

Count ++;

BaskItem baskItem =This. GetBaskItemById (baskItemId, buyerId );

If(BaskItem! =Null){

...;

}

}

There are many preventive measures to avoid object changes caused by exceptions.

① Check the parameters before performing the operation. If the parameters are incorrect, an exception is thrown to avoid changing the object value in subsequent operations. (In fact, parameter verification is a good practice before a method starts. It not only avoids object changes caused by exceptions, but also avoids unnecessary overhead .)

② Adjust the processing sequence so that any operations that may cause object changes may be called after an exception.

③ Write a recovery code after an exception is caught for rollback.

④ Copy an object and perform operations on the object copy. After Execution, replace the original object with the copied object.

Of course, it does not mean to keep the atomicity of failure for any exceptions. If a method throws an error, it makes little sense to keep the atomicity of failure storage. For example, if an OutOfMemoryError occurs, it is unnecessary to restore the error.

2.6 do not capture all exceptions at once

In our code, we often see the following code once and for all.

Try {

...... ...... // Throw an AException

...... ...... // Throw BException

...... ...... // Throw a CException

} Catch(Exception e ){

Log. error ("XXX error", e. getCause ());

}

This code is characterized by capturing all exceptions with a catch clause, which seems much easier. There are actually defects. First, there may be different recovery measures for different exceptions, and the code here makes it impossible for us to differentiate exceptions, so we cannot recover them accordingly. Second, this method masks RuntimeException exceptions in the code. Generally, RuntimeException is a programming error. That is, this method masks our programming errors.

For a piece of code, multiple calls may produce exceptions. We can capture each exception and handle it differently.

2.7 Use of checked exceptions for recoverable situations and runtime exceptions for programming errors

This makes it clear that the differences between checked exceptions and unchecked exceptions are not difficult to understand. An exception that must be caught during compilation. The purpose of exception capture is to take some measures to recover the exception. If we want the caller to take remedial measures after an error occurs when calling our method, we should throw a checked exception. For some programming errors, we hope that the caller can avoid them in the code. At this time, an unchecked exception RuntimeException should be thrown, prompting the caller to improve the code. For example, the IndexOutOfBoundsException exception mentioned above should be avoided in the code.

2.8 release resources in finally Blocks

For some operations, such as IO, Socket, or database operations, when an exception occurs, we also need to correctly release the occupied resources. In general, we release resources in the finally block. It is worth noting that clauses in the finally block may also encounter exceptions. We should try to avoid such exceptions during encoding. As follows:

Try{

......

Reader =NewBufferedReader (NewInputStreamReader (

NewFileInputStream (file )));

For(String record = reader. readLine (); record! =Null {

......

}

} Catch(FileNotFoundException e ){

Log. error ("error while reading file" + file. getName ());

} Catch(IOException e ){

Log. error ("error while reading file" + file. getName () + e );

} Catch(Exception e ){

Log. error ("baskitem task failed... ");

} Finally {

Try {

Reader. close ();

} Catch(IOException e ){

Log. error ("error while closeing file" + file. getName ());

}

}

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.