A Java exception is an object that describes an exception (that is, an error) situation that occurs in a code segment. When an exception occurs, an object representing the exception is created and thrown in the method that causes the error. This method can choose to handle the exception itself or pass it. In both cases, the exception is caught and processed. The exception may be generated by the Java runtime system, or by your manual code. The exception thrown by Java is related to basic errors that violate language specifications or exceed the limitations of Java execution environment. The exceptions generated by manual encoding are basically used to report error conditions in the method caller.
Java exception handling is controlled by 5 keywords: try, catch, throw, throws and finally. Here is how they work. The program declares that the exception monitoring you want is included in a try block. If an exception occurs in the try block, it is thrown. Your code can catch this exception (with catch) and handle it in some reasonable way. The exception generated by the system is automatically thrown by the Java runtime system. Manually throw an exception, using the keyword throw. Any exception to the thrown method must be defined by the throws clause. Any code that is absolutely executed before the method returns is placed in the finally block.
Here is the usual form of an exception handling block:
try { // block of code to monitor for errors}catch (ExceptionType1 exOb) { // exception handler for ExceptionType1}catch (ExceptionType2 exOb) { // except ion handler for ExceptionType2}// ... finally { // block of code to be executed before try block ends}
Here, ExceptionType is the type where the exception occurred.
All exception types are subclasses of the built-in class Throwable. Therefore, Throwable is at the top level of the exception class hierarchy. Immediately following Throwable are two subclasses that divide the exception into two different branches. A branch is Exception.
This class is used for exceptions that may be caught by the user program. It is also a class you can use to create your own user exception type subclass. There is an important subclass RuntimeException in the Exception branch. This type of exception is automatically defined for the program you write and includes errors such as dividing by zero and illegal array indexing.
Another type of branch is top-level with Error, which defines exceptions that are not intended to be caught by programs in normal environments. An exception of type Error is used in Java runtime system to display errors related to the runtime system itself. Stack Overflow is an example of this error. This chapter will not discuss exception handling for Error types, because they are often catastrophic and fatal errors that are not something your program can control.