What is an exception, why should we care about it --The Java Tutorial - Exception Section 1

zhaozj2021-02-17  49

Trail: Essential Java Classes

Lesson: Handling Errors with Exceptions

What is an abnormality, why should we care about it?

The word "exception" is the abbreviation of the phrase "Exceptional Event", which is defined as follows:

Definition: An exception is an event that occurs when executed, which interrupts the normal flow of the instruction.

Many types of errors will trigger an exception. These problems are from crashing such as a hard drive (Crash). The simple program error that is trying to access the cross-boundary array element. If such an error occurs in the Java function, the function will create one Abnormal objects and throw him to runtime system. Abnormal objects contain an exception, including the type of abnormality, the state of the program when an exception occurs. Runtime system is responsible for finding some code to process this error. In the Java Technical Dictionary, create an exception object and throw it to the runtime system called: Throwing An Exception.

When a function throws an exception, the runtime system jumped into such actions, that is, find some people (the translator's note: actually code) to handle this exception. The collection of possible people (code) to be found (SET) is: Collection of methods in the call stack in the Call Stack occurred in an abnormal method (SET). Running the system backward search calling stack, from an error, until a function that includes a suitable exception handler is found. Is an exception processor suitable depends on whether the abnormality throwing is abnormal and an exception processor processing is the same type. Since the abnormality is looking for the entire call stack until a qualified exception processor is found, the call function processing this exception. The choice of an exception processor is called: Catch the Exception.

If the runtime system search the entire call stack does not find the appropriate exception processor, the system will end, and the Java program will also end.

Use an exception to manage errors, which is the following advantages over traditional error management techniques:

1. Separate the error handling code on the normal code.

2. Pass an error in the call stack.

3. Participate the error and distinguish between error types.

1. Separate the error handling code on the normal code.

In traditional programming, error detection, reporting, and processing, it often leads to a fascinated code of spaghetti. For example, suppose you want to write a function that reads this file to the memory, description by a dummy code, your function should be this:

Readfile {

Open the file; // Open the file

DETERMINE ITS SIZE; / / Size of the file

Allocate That Much Memory; // Assign Memory

Read the file info memory; // Read file content to memory

Close the file; // Close file

}

In a hurry, this version is simple enough, but it ignores all potential questions:

N files can't open what will happen?

N file size can't get what happened? N What will happen not enough memory allocation?

n What happens when reading failed?

N files can't be closed?

In order to answer these errors in the read_file function, you have to add a lot of code to make error detection, report, and processing, your function will look like this:

ErrorCodetype Readfile {

Initialize ErrorCode = 0;

Open the file;

IF (thefileiSopen) {

DETERMINE.

gotthefilelength) {

ALLOCATE THAT MUCH MEMORY;

IF (gotenoughmemory) {

Read the file info memory;

IF (readfailed) {

ErrorCode = -1;

}

} else {

ErrorCode = -2;

}

} else {

ErrorCode = -3;

}

Close the file;

IF (ThefiledIDIDNTCLOSE & & & & ErrorCode == 0) {

ErrorCode = -4;

} else {

ErrorCode = ErrorCode and -4;

}

} else {

ErrorCode = -5;

}

Return ErrorCode;

}

With the establishment of mistroduction, your original 7-line code (bold) has quickly expanded to 29 lines - almost 400% expansion rate. Worse, there is such an error detection, report, and error return value, making the initial 7-line code flooded in chaos, the logic flow of the code was also submerged. It is difficult to answer the correct thing to answer the code: if the function assignment content fails, will the file really turn it off? It's more difficult to determine if you change the code again after three months, it can also be executed correctly. Many programmers "Solve" this problem is simple to ignore it, as mistakes will be reported in a crash.

For error management, Java provides an elegant solution: exception. An exception can separate the primary proxidation in your code and the code for processing exceptions. If you use an exception instead of traditional error management technology, the ReadFile function will look like this:

Readfile {

Try {

Open the file;

DETERMINE ITS SIZE;

ALLOCATE THAT MUCH MEMORY;

Read the file info memory;

Close the file;

} catch (fileopenfailed) {

DOSMETHING;

} catch (sizedeeeeterminationfailed) {

DOSMETHING;

} catch (memoryAlocationfailed) {

DOSMETHING;

} catch (readfailed) {

DOSMETHING;

} catch (fileclosefailed) {

DOSMETHING;

}

}

Note: Exceptions do not save you efforts to detect, report, and handle errors. Exceptions to you is: When some abnormal things happen, put all the details of the gruny, from your program master logic process.

In addition, the expansion coefficient of abnormal error management is approximately 250%, which is more than 400% of the traditional error handling technology.

2. Pass an error in the call stack.

The second advantage of the abnormality is that the error can be reported upward along the call stack of the function. Imagine that the readfile function is a fourth function in a series of nested calls: Method1 calls Method2, Method2 calls Method3, and finally Method3 call ReadFile. Method1 {

Call method2;

}

Method2 {

Call method3;

}

Method3 {

Call readfile;

}

If Method1 is interested in errors that occur in ReadFile. Traditional error notification techniques forced MOTHED2 and MOTHED3 to deliver ReadFile's error code along the calling stack until the MOTHED1 that is interested in errors.

Method1 {

ErrorCodetype error;

Error = Call method2;

IF (Error)

DoerrorProcessing;

Else

Proceed;

}

ErrorCodetype method2 {

ErrorCodetype error;

Error = Call method3;

IF (Error)

Return Error;

Else

Proceed;

}

ErrorCodetype method3 {

ErrorCodetype error;

Error = Call ReadFile;

IF (Error)

Return Error;

Else

Proceed;

}

As mentioned earlier, the Java runtime system is backward (BASKWARD, that is, up) Search the calling stack to find a function that is interested in processing this exception. The Java function can "avoid the exception thrown in the function, so the function is allowed to pass through the call stack capture. The only function Method1 that is interested in errors will be responsible for detection errors.

Method1 {

Try {

Call method2;

} catCH (Exception) {

DoerrorProcessing;

}

}

Method2 throws exception {

CALL METHOD3;

}

Method3 throws exception {

Call readfile;

}

However, as you can see in pseudo code, in the "middleman (middle function METHOED2 and METHOD3)" ignore the exception needs to be affected, if you want to throw an exception, you must use throws in the public interface declaration of the function. Keyword specified. Therefore, a function can notify it that the caller will throw something such an exception, so that the caller can consciously do something about these exceptions.

Again pay attention to an abnormality and the traditional error handling method, the difference between the expansion coefficient and the inclusion coefficient. Using an abnormal code is more concise, it is easier to understand.

3. Participate the error and distinguish between error types.

Abnormal (we) is often divided into categories or groups. For example, you can imagine a set of exceptions, each representing a special exception for array operations: index beyond the range of array, the element to be inserted is an error, the elements to find are not in array. Moreover, you can imagine that some functions will handle all such exceptions (About arrays), and some other functions will handle special exceptions (only invalid index exception).

Since all abnormalities in the Java program is first object, exception packets and classifications becomes a class inheritance natural result. Java exception must be Throwable or an example of the throwable subclass. Just like you can inherit from other Java class, you can also create a subclass of Thowable, or grandson (inherited from the Thowable subclass). Each leaf node (there is no subclass) represents a special type of exception, and each node (Node) (class with one or more subclasses) represents a group of associated exceptions. For example, in the following chart, ArrayException is the subclass of Exception (a subclass of throwable), which has three subclasses.

InvalidIndexexception, ElementTyPeException, and Nosuchelementexception are all leaves, which are errors that occur when operating arrays. One way to capture an abnormality is to capture only examples of leaf classes. For example, an exception controller simply capturing an invalid index exception, its code looks like this:

Catcatch (InvalidIndexexception E) {

.

}

Arrayexecption is a node (Node) class that represents any errors that occur when you operate arrays, including any one of all subclasses that represent an error. If a function is a group or a class of exceptions, as long as these exceptions are specified in the CATHC statement (SuperClass). For example, to capture all array exceptions without specifying a specific type, the exception controller will capture ArrayException:

Catch (arrayexception e) {

.

}

This exception controller will capture all array exceptions, including InvalidIndexException, ElementTyPeException, and Nosuchelementexception. You can find an exceptional type in the parameter E of an exception controller. You can even build such an exception controller, which processes all of Exception.

Catch (Exception E) {

.

}

The exception controller shown above is too universal, doing so that your code handles too much error, you need to handle many exceptions you don't want to handle, so you can't process an exception. Usually we don't recommend writing a general unusual processor.

As you can see, you can create a set of exceptions and handle these exceptions in a general way; you can specify an exception type to distinguish an exception, and process an exception in an accurate way.

What's next?

Now you can understand the use of exceptions in the Java program, now I am going to learn how to use them.

转载请注明原文地址:https://www.9cbs.com/read-29603.html

New Post(0)