Handling errors with exceptions-Section 2 benefits of exception management

Source: Internet
Author: User

You have read about exceptions and how to use them. It is time to learn the benefits of using exceptions in your program.

Advantage 1: separating rule code from error handling code

Exception Handling requires that the detailed work required when an error occurs be separated from the main logic code of the program. In traditional programs, error discovery, reporting, and handling often make code messy. For example, consider the following pseudo code, which is a method to read the entire file into the memory.

1. readfile {
2. open the file;
3. determine its size;
4. Allocate that much memory;
5. Read the file into memory;
6. close the file;
7 .}
8.

At first glance, this function seems very simple, but it ignores the possibility of the following errors.

1. What will happen if the file cannot be opened?
2. What happens if the file size cannot be determined?
3. What will happen if there is not enough memory?
4. What will happen if reading fails?
5. If the file cannot be closed. What will happen?

To process this information, the readfile function must use more code for error discovery, reporting, and processing. This function may look like this:

1. errorcodetype readfile {
2. initialize errorcode = 0;
3. open the file;
4. If (thefileisopen ){
5. determine the length of the file;
6. If (gotthefilelength ){
7. Allocate that much memory;
8. If (gotenoughmemory ){
9. Read the file into memory;
10. If (readfailed ){
11. errorcode =-1;
12 .}
13. else {
14. errorcode =-2;
15 .}
16.} else {
17. errorcode =-3;
18 .}
19. close the file;
20. If (thefiledidntclose & errorcode = 0 ){
21. errorcode =-4;
22.} else {
23. errorcode = errorcode and-4;
24 .}
25.} else {
26. errorcode =-5;
27 .}
28. Return errorcode;
29 .}
30.

With so many error discoveries, reports, and responses, the first seven lines of code are not buried in the messy error code. More seriously, the logic flow of the Code is gone, which makes it difficult to indicate whether the code is doing the right thing: if the function fails to allocate memory, is the file really closed? It is even more difficult to ensure that the code you wrote will continue to do the right thing three months later.
Exception Handling allows you to write the main workflow of code and handle exception information elsewhere. If the readfile function uses Exception Handling instead of the traditional error management technology, it should be like the following code:
1. readfile {
2. Try {
3. open the file;
4. determine its size;
5. Allocate that much memory;
6. Read the file into memory;
7. close the file;
8.} catch (fileopenfailed ){
9. dosomething;
10.} catch (sizedeterminationfailed ){
11. dosomething;
12.} catch (memoryallocationfailed ){
13. dosomething;
14.} catch (readfailed ){
15. dosomething;
16.} catch (fileclosefailed ){
17. dosomething;
18 .}
19 .}
20.

Note: Exception Handling does not save on error discovery, reporting, and processing workload, but it helps you organize code more effectively.

Advantage 2: Passing errors to the upper layer of the Call Stack
The second advantage of exception handling is the ability to pass error reports to the upper layer of the method call stack. Assume that the readfile method is the fourth method in a series of nested methods called by the main program: method 1 call method 2, method 2 call method 3, and method 3 call readfile. The code structure is as follows:
1. Method1 {
2. Call method2;
3 .}
4. method2 {
5. Call method3;
6 .}
7. method3 {
8. Call readfile;
9 .}
10.
If Method1 is the only method that can handle errors that may occur in the readfile method, the traditional error processing technology will force method2 and method3 to pass the error code returned by calling the stack through readfile, until the error code is passed to Method1-because only Method1 can handle these errors, the code structure is as follows:
1. Method1 {
2. errorcodetype error;
3. Error = call method2;
4. If (error)
5. doerrorprocessing;
6. Else
7. Proceed;
8 .}
9. errorcodetype method2 {
10. errorcodetype error;
11. Error = call method3;
12. If (error)
13. Return Error;
14. Else
15. Proceed;
16 .}
17. errorcodetype method3 {
18. errorcodetype error;
19. Error = call readfile;
20. If (error)
21. Return Error;
22. Else
23. Proceed;
24 .}
25.
Recall that the Java Runtime Environment searches for call stacks to find any methods to handle special exceptions. A method can throw any internal exceptions, So it allows an upper-layer method to call the stack to capture it. Therefore, the code structure is as follows:
1. Method1 {
2. Try {
3. Call method2;
4.} catch (exception e ){
5. doerrorprocessing;
6 .}
7.
8 .}
9. method2 throws exception {
10. Call method3;
11 .}
12. method3 throws exception {
13. Call readfile;
14 .}
15.
In any case, as the pseudocode shows, the intermediate method is required to avoid exceptions. Any exceptions thrown by internal methods that are detected must be specified in the throws clause of this method.
Advantage 3: grouping and distinguishing error types
Because all exceptions thrown in the program are objects, the exception group or category is the natural result of class inheritance. An example of a group of related exception classes on the Java platform is the ioexception and its subclass defined in Java. Io. Ioexception is the most common Io Exception management class and describes any types of errors that occur when I/O operations are performed. Its subclass describes some special errors. For example, the filenotfoundexception exception class indicates that a file cannot be found on the local disk.
A method can write a special exception processor so that it can handle very special exceptions. The filenotfoundexception exception class does not have any subclass. Therefore, the following exception processor can only handle one exception type:
Catch (filenotfoundexception e ){
...
}
A method can capture exceptions based on its grouping or by the general type of any exceptions specified in the catch clause. For example, to capture all I/O exceptions regardless of their type, you can specify an ioexception parameter in the exception processor:
Catch (ioexception e ){
...
}
This processor will capture all I/O exceptions, including filenotfoundexception and eofexception. You can find the error details by querying the parameters passed to the exception processor. For example, print the stack execution route:
Catch (ioexception e ){
E. printstacktrace (); // output goes to sytem. Err
E. printstacktrace (system. Out); // send trace to stdout
}
You can even create an exception processor that can handle any type of exceptions:
Catch (exception e) {// A (too) general exception handler
...
}
The exception class is the top-level class in the throwable class structure. Therefore, this processor will capture exceptions except those caught by a specific processor. You may wonder if your program is using this method to handle exceptions. For example, print an error message for the user and exit.
However, in most cases, you need an exception processor to be as accurate as possible. The reason is that before the processor determines the best recovery policy, it must first determine the type of exception. If no specific error is captured, the processor must effectively provide any possibility. The exception processor is the most common exception processor. This processor enables code to capture and handle unexpected error tendencies of more programmers, making the processor unpurposeful.
As we show, you can create exception groups and handle exceptions in a general manner, or identify exceptions using specific exception types and use precise methods to handle exceptions. The next section describes how to capture and handle exceptions.

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.