Wednesday 16 March 2016

The Java Language: Exceptions

Java has its roots in embedded systems—software that runs inside specialized devices, such as handheld computers, cellular phones, and fancy toasters. In those kinds of applications, it’s especially important that software errors be handled robustly. Most users would agree that it’s unacceptable for their phone to simply crash or for their toast (and perhaps their house) to burn because their software failed. Given that we can’t eliminate the possibility of software errors, it’s a step in the right direction to recognize and deal with anticipated application-level errors methodically. Dealing with errors in some languages is entirely the responsibility of the programmer. The language itself provides no help in identifying error types and no tools for dealing with them easily. In the C language, a routine generally indicates a failure by returning an “unreasonable” value (e.g., the idiomatic -1 or null). As the programmer, you must know what constitutes a bad result and what it means. It’s often awkward to work around the limitations of passing error values in the normal path of data flow. An even worse problem is that certain types of errors can legitimately occur almost anywhere, and it’s prohibitive and unreasonable to explicitly test for them at every point in the software. Java offers an elegant solution to these problems through exceptions. (Java exception handling is similar to, but not quite the same as, exception handling in C++.) An exception indicates an unusual condition or an error condition. Program control becomes unconditionally transferred or “thrown” to a specially designated section of code where it’s caught and handled. In this way, error handling is orthogonal to (or independent of) the normal flow of the program. We don’t have to have special return values for all of our methods; errors are handled by a separate mechanism. Control can be passed a long distance from a deeply nested routine and handled in a single location when that is desirable, or an error can be handled immediately at its source. A few standard Java API methods still return -1 as a special value, but these are generally limited to situations where we are expecting a special value and the situation is not really out of bounds. A Java method is required to specify the exceptions it can throw (i.e., the ones that it doesn’t catch itself), and the compiler makes sure that callers of the method handle them. In this way, the information about what errors a method can produce is promoted to the same level of importance as its argument and return types. You may still decide to punt and ignore obvious errors, but in Java you must do so explicitly. (We’ll discuss “runtime exceptions,” which are not required to be declared or handled by the method, in a moment.)

0 comments:

Post a Comment