Answer to Question #42826 in Other Programming & Computer Science for solomon

Question #42826
What is exception in programming concept?
Expert's answer

The term exception is shorthand for the phrase"exceptional event."

Definition: An exceptionis an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.

When an error occurs within a method, the methodcreates an object and hands it off to the runtime system. The object, called an
exception object, contains information about the error, including itstype and the state of the program when the error occurred. Creating an
exception object and handing it to the runtime system is called throwing anexception.
After a method throws an exception, the runtime systemattempts 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.
The runtime system searches the call stack for a methodthat contains a block of code that can handle the exception. This block of code
is called an exception handler. The search begins with the method inwhich the error occurred and proceeds through the call stack in the reverse
order in which the methods were called. When an appropriate handler is found,
the runtime system passes the exception to the handler. An exception handler is
considered appropriate if the type of the exception object thrown matches the
type that can be handled by the handler.
The exception handler chosen is said to catch theexception. If the runtime system exhaustively searches all the methods onthe call stack without finding an appropriate exception handler, as shown in the
next figure, the runtime system (and, consequently, the program) terminates.
Using exceptions to manage errors has some advantagesover traditional error-management techniques.
Advantages of ExceptionsNow thatyou know what exceptions are and how to use them, it's time to learn the
advantages of using exceptions in your programs.
Advantage 1: Separating Error-Handling Code from"Regular" Code
Exceptionsprovide the means to separate the details of what to do when something out of
the ordinary happens from the main logic of a program. In traditional
programming, error detection, reporting, and handling often lead to confusing
spaghetti code. For example, consider the pseudocode method here that reads an
entire file into memory.
readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file;}At firstglance, this function seems simple enough, but it ignores all the following
potential errors.
What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed?To handlesuch cases, the
function must have more code to do errordetection, reporting, and handling. Here is an example of what the function
might look like.
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;}There'sso much error detection, reporting, and returning here that the original seven
lines of code are lost in the clutter. Worse yet, the logical flow of the code
has also been lost, thus making it difficult to tell whether the code is doing
the right thing: Is the file really being closed if the function fails to allocate
enough memory? It's even more difficult to ensure that the code continues to do
the right thing when you modify the method three months after writing it. Many
programmers solve this problem by simply ignoring it - errors are reported when
their programs crash.
Exceptionsenable you to write the main flow of your code and to deal with the exceptional
cases elsewhere. If the
function used exceptions instead oftraditional 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; }}Note thatexceptions don't spare you the effort of doing the work of detecting,
reporting, and handling errors, but they do help you organize the work more
Advantage 2: Propagating Errors Up the Call Stack
A secondadvantage of exceptions is the ability to propagate error reporting up the call
stack of methods. Suppose that the
method is the fourth method in a series ofnested method calls made by the main program:
, which calls
, which finallycalls
method1 { call method2;} method2 { call method3;} method3 { call readFile;}Supposealso that
is the only method interested in theerrors that might occur within
. Traditionalerror-notification techniques force
to propagate the error codes returned by
up the call stack until the error codesfinally reach
—the only methodthat is interested in them.
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;}Recallthat the Java runtime environment searches backward through the call stack to
find any methods that are interested in handling a particular exception. A
method can duck any exceptions thrown within it, thereby allowing a method
farther up the call stack to catch it. Hence, only the methods that care about
errors have to worry about detecting errors.
method1 { try { call method2; } catch (exception e) { doErrorProcessing; }} method2 throws exception { call method3;} method3 throws exception { call readFile;}However,as the pseudocode shows, ducking an exception requires some effort on the part
of the middleman methods. Any checked exceptions that can be thrown within a
method must be specified in its
Advantage 3: Grouping and Differentiating Error Types
Becauseall exceptions thrown within a program are objects, the grouping or
categorizing of exceptions is a natural outcome of the class hierarchy. An
example of a group of related exception classes in the Java platform are those
defined in
and its descendants.
is the most general and represents anytype of error that can occur when performing I/O. Its descendants represent
more specific errors. For example,
means that a file could not be located ondisk.
A methodcan write specific handlers that can handle a very specific exception. The
class has no descendants, so the followinghandler can handle only one type of exception.
catch (FileNotFoundException e) { ...}A methodcan catch an exception based on its group or general type by specifying any of
the exception's superclasses in the
statement. For example, to catch all I/Oexceptions, regardless of their specific type, an exception handler specifies
catch (IOException e) { ...}Thishandler will be able to catch all I/O exceptions, including
, and so on. Youcan find details about what occurred by querying the argument passed to the
exception handler. For example, use the following to print the stack trace.
catch (IOException e) { // Output goes to System.err. e.printStackTrace(); // Send trace to stdout. e.printStackTrace(System.out);}You couldeven set up an exception handler that handles any
with the handler here.
// A (too) general exception handlercatch (Exception e) { ...}The
class is close to the top of the
class hierarchy. Therefore, this handlerwill catch many other exceptions in addition to those that the handler is
intended to catch. You may want to handle exceptions this way if all you want
your program to do, for example, is print out an error message for the user and
then exit.
In mostsituations, however, you want exception handlers to be as specific as possible.
The reason is that the first thing a handler must do is determine what type of
exception occurred before it can decide on the best recovery strategy. In
effect, by not catching specific errors, the handler must accommodate any
possibility. Exception handlers that are too general can make code more
error-prone by catching and handling exceptions that weren't anticipated by the
programmer and for which the handler was not intended.
As noted,you can create groups of exceptions and handle exceptions in a general fashion,
or you can use the specific exception type to differentiate exceptions and
handle exceptions in an exact fashion.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

New on Blog