A brief look at the use of exception handling in Java programming

  • 2020-04-01 04:13:13
  • OfStack

A Java exception is an object that describes an exception (that is, an error) that occurs in a snippet of code. When an exception occurs, an object representing the exception is created and thrown in the method that caused the error. The method can choose to handle the exception itself or pass it. In both cases, the exception is caught and handled. Exceptions may be generated by the Java runtime system or by your manual code. Exceptions thrown by Java are related to basic errors that violate language specifications or exceed the limits of the Java execution environment. Hand-coded exceptions are basically used to report an error condition in a method caller.

Java exception handling is controlled by five keywords: try, catch, throw, throw, and finally. Here's how they work. The program declares that the exception monitoring you want is contained in a try block. If an exception occurs in the try block, it is thrown. Your code can catch the exception (with catch) and handle it in a reasonable way. Exceptions generated by the system are thrown automatically by the Java runtime system. Throw an exception manually, using the keyword throw. Any exception to a thrown method must be defined by the throws clause. Any code that is absolutely executed before the method returns is placed ina 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) {
  // exception handler for ExceptionType2
}
// ...
finally {
  // block of code to be executed before try block ends
}

In this case, ExceptionType is the type of exception that occurred.

All exception types are subclasses of the built-in class Throwable. Therefore, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that divide the exception into two different branches. One branch is Exception.

This class is used for exceptions that a user program might catch. It is also a class that you can use to create your own subclass of user exception types. There is an important subclass RuntimeException in the Exception branch. This type of exception is automatically defined for your program and includes errors such as zero division and illegal array indexing.

Another kind of branch is topped off by an Error, which defines exceptions that the program would not want to catch under normal circumstances. Error-type exceptions are used by the Java runtime system to display errors related to the runtime system itself. A stack overflow is an example of this error. This chapter will not discuss exception handling for Error types, as they are often catastrophic and fatal errors that are beyond your program's control.


Related articles: