Concepts of Programming Languages

(Sean Pound) #1
14.4 Exception Handling in Java 647

catch(NegativeInputException& e) { //**Handler for
//** negative input
cout << "Limits Frequency" << endl;
for (index = 0; index < 10; index++) {
limit_1 = 10 * index;
limit_2 = limit_1 + 9;
if (index == 9)
limit_2 = 100;
cout << limit_1 << limit_2 << freq[index] << endl;
} //* end of for (index = 0)
} //* end of catch (NegativeInputException& e)
} //* end of main

This program is meant to illustrate the mechanics of C++ exception handling. Note
that the index range exception is often handled in C++ by overloading the indexing
operation, which could then raise the exception, rather than the direct detection of
the indexing operation with the selection construct used in our example.

14.3.6 Evaluation


In some ways, the C++ exception-handling mechanism is similar to that of
Ada. For example, unhandled exceptions in functions are propagated to the
function’s caller. However, in other ways, the C++ design is quite different:
There are no predefined hardware-detectable exceptions that can be handled
by the user, and exceptions are not named. Exceptions are connected to han-
dlers through a parameter type in which the formal parameter may be omitted.
The type of the formal parameter of a handler determines the condition under
which it is called but may have nothing whatsoever to do with the nature of the
raised exception. Therefore, the use of predefined types for exceptions certainly
does not promote readability. It is much better to define classes for exceptions
with meaningful names in a meaningful hierarchy that can be used for defining
exceptions. The exception parameter provides a way to pass information about
an exception to the exception handler.

14.4 Exception Handling in Java


In Chapter 13, the Java example program includes the use of exception
handling with little explanation. This section describes the details of Java’s
exception-handling capabilities.
Java’s exception handling is based on that of C++, but it is designed to be
more in line with the object-oriented language paradigm. Furthermore, Java
includes a collection of predefined exceptions that are implicitly raised by the
Java Virtual Machine ( JVM).
Free download pdf