"When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception."
1,error occurs,and then creats object(containing information about the error,such as its type and the state of the program),hands it off to the runtime system.
2,throwing an exception:creating an exception object and handing it to the runtime system.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).
3,after throwing an exception,RUNTIME System attempts to find something to handle it. the "something":the ordered list of methods.:call stack!!!
4,exception handler:
5,catch the exception:the exception handler chosen.
Advantages of Exceptions:
Advantage 1: Separating Error-Handling Code from "Regular" Code:Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program.(potential errors)
from"readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}" to
"errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}" leads to "original seven lines of code are lost in the clutter"
worse yet:difficult to tell whether the code is doing the right thing
Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere. If the readFile function used exceptions instead of traditional error-management techniques, it would look more like the following.:
readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (sizeDeterminationFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
Advantage 2: Propagating Errors Up the Call Stack:
A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods.
Advantage 3: Grouping and Differentiating Error Types:
(to be continued)