Chapter 4 Exceptions and MultithreadingJava Programming (9113) by T. B. Kute
Exception is a condition that is caused by run-time error in theprogram. In computer programming languages that do not supportexception handling, errors must be checked and handled manuallythrough the use of error codes, and so on. But this approach iscumbersome as well as troublesome. Java’s exception handling avoidsthese problems and, in the process and brings run-time errormanagement into the object-oriented world. C++ programming languagesupports exception handling but Java has enhanced some of its features.As Java is strictly object oriented, an exception is also an objectthat describes an exceptional (that is, error) condition that has occurredin a piece of source code. When an exceptional condition arises inprogram, an object representing that exception is created and thrown inthe method that caused the error. That method may choose to handle theexception itself, or pass it on. Exceptions can be generated by the Javarun-time system, or they can be manually generated by our code.Exceptions thrown by Java relate to fundamental errors that violate therules of the Java language or the constraints of the Java executionenvironment. Manually generated exceptions are typically used to reportsome error condition to the caller of a method.The purpose of exception handling mechanism is to provide ameans to detect and to report exceptional circumstances so thatappropriate action can be taken. The mechanism suggests incorporationof separate error handling code that performs following tasks:
Find the problem
Inform about error has occurred
Receive the error information
Take the corrective actionJava’s exception handling mechanism provides every step to beimplemented.
Types of Exceptions
All exception types in Java are subclasses of the built-in abstractclass java.lang.Throwable. Thus, Throwable is at the top of the exceptionclass hierarchy. There are two subclasses that partition exceptions intotwo distinct categories. That is Exception and Error. First category isException. This class is used for exceptional conditions that userprograms should catch. This is also the class that we will subclass tocreate our own exception types.There is an important subclass of Exception, calledRuntimeException. Exceptions of this type are automatically defined forthe programs that we write and include things such as division by zeroand invalid array indexing. Second category of exceptions is Error, whichdefines exceptions that are not expected to be caught under normalcircumstances by the program. Exceptions of type Error are used by the