Catching Exceptions in java - Core Java

You now know how to throw an exception. It is pretty easy. You throw it and you forget it. Of course, some code has to catch the exception. Catching exceptions requires moreplanning. If an exception occurs that is not caught anywhere, the program will terminate and print a message to the console, giving the type of the exception and a stack trace. Graphics programs (both applets and applications) catch exceptions, print stack trace messages, and then go back to the user interface processing loop. (When you are debugging a graphically based program, it is a good idea to keep the console available on the screen and not minimized.)

To catch an exception, you set up a try/catch block. The simplest form of the try block is as follows:

If any of the code inside the try block throws an exception of the class specified in the catch clause, then

1. The program skips the remainder of the code in the try block.
2. The program executes the handler code inside the catch clause.

If none of the code inside the try block throws an exception, then the program skips the catch clause. If any of the code in a method throws an exception of a type other than the one named in the catch clause, this method exits immediately. (Hopefully, one of its callers has already coded a catch clause for that type.) To show this at work, we show some fairly typical code for reading in data:

Notice that most of the code in the try clause is straightforward: it reads and processes bytes until we encounter the end of the file. As you can see by looking at the Java API, there is the possibility that the read method will throw an IOException. In that case, we skipout of the entire while loop, enter the catch clause and generate a stack trace. For a toyprogram, that seems like a reasonable way to deal with this exception. What other choice do you have?

Often, the best choice is to do nothing at all and simply pass the exception on to the caller. If an error occurs in the read method, let the caller of the read method worry about it! If we take that approach, then we have to advertise the fact that the method may

Remember, the compiler strictly enforces the throws specifiers. If you call a method that throws a checked exception, you must either handle it or pass it on. Which of the two is better? As a general rule, you should catch those exceptions that you know how to handle and propagate those that you do not know how to handle.

When you propagate an exception, you must add a throws specifier to alert the caller that an exception may be thrown.

Look at the Java API documentation to see what methods throw which exceptions. Thendecide whether you should handle them or add them to the throws list. There is nothingembarrassing about the latter choice. It is better to direct an exception to a competent handler than to squelch it.

Please keep in mind that there is one exception to this rule, as we mentioned earlier. If you are writing a method that overrides a superclass method that throws no exceptions(such as paintComponent in JComponent), then you must catch each checked exception in the method’s code. You are not allowed to add more throws specifiers to a subclass method than are present in the superclass method.

Catching Multiple Exceptions

You can catch multiple exception types in a try block and handle each type differently. You use a separate catch clause for each type as in the following example:

The exception object (e1, e2, e3) may contain information about the nature of the exception.

To find out more about the object, try

to get the detailed error message (if there is one), or

to get the actual type of the exception object.

Rethrowing and Chaining Exceptions

You can throw an exception in a catch clause. Typically, you do this because you want to change the exception type. If you build a subsystem that other programmers use, it makes a lot of sense to use an exception type that indicates a failure of the subsystem.

An example of such an exception type is the ServletException. The code that executes aservlet may not want to know in minute detail what went wrong, but it definitely wants to know that the servlet was at fault. Here is how you can catch an exception and rethrow it:

Here, the ServletException is constructed with the message text of the exception. As of Java SE 1.4, you can do better than that and set the original exception as the “cause” of the new exception:

When the exception is caught, the original exception can be retrieved:

This wrapping technique is highly recommended. It allows you to throw high-level exceptions in subsystems without losing the details of the original failure.

The finally Clause

When your code throws an exception, it stops processing the remaining code in your method and exits the method. This is a problem if the method has acquired some local resource that only it knows about and if that resource must be cleaned up. One solution is to catch and rethrow all exceptions. But this solution is tedious because you need to clean up the resource allocation in two places, in the normal code and in the exception code.

Java has a better solution, the finally clause. Here we show you how to properly dispose of a Graphics object. If you do any database programming in Java, you will need to use thesame techniques to close connections to the database.It is very important to close all database connections properly, even when exceptions occur.

The code in the finally clause executes whether or not an exception was caught. In the following example, the program will dispose of the graphics context under all circumstances:

Let us look at the three possible situations in which the program will execute thefinally clause.

  1. The code throws no exceptions. In this event, the program first executes all the code in the try block. Then, it executes the code in the finally clause. Afterwards, execution continues with the first statement after the finally clause. In other words, execution passes through points 1, 2, 5, and 6.
  2. The code throws an exception that is caught in a catch clause, in our case, an IOException. For this, the program executes all code in the try block, up to the point at which the exception was thrown. The remaining code in the try block is skipped. The program then executes the code in the matching catch clause, then the code in the finally clause.

    If the catch clause does not throw an exception, the program executes the first line after the finally clause. In this scenario, execution passes through points 1, 3, 4, 5, and 6.

    If the catch clause throws an exception, then the exception is thrown back to the caller of this method, and execution passes through points 1, 3, and 5 only.

  3. The code throws an exception that is not caught in any catch clause. For this, the program executes all code in the try block until the exception is thrown. The remaining code in the try block is skipped. Then, the code in the finally clause is executed, and the exception is thrown back to the caller of this method. Execution passes through points 1 and 5 only.

You can use the finally clause without a catch clause. For example, consider the following try statement:

The in.close() statement in the finally clause is executed whether or not an exception is encountered in the try block. Of course, if an exception is encountered, it is rethrown and must be caught in another catch clause. In fact, as explained in the following tip, we think it is a very good idea to use the finally clause in this way whenever you need to close a resource.

The inner try block has a single responsibility: to make sure that the input stream is closed. The outer try block has a single responsibility: to ensure that errors are reported. Not only is this solution clearer, it is also more functional: errors in the finally clause are reported.

If you call f(2), then the try block computes r = 4 and executes the return statement. However, the finally clause is executed before the method actually returns. The finally clause causes the method to return 0, ignoring the original return value of 4.

Sometimes the finally clause gives you grief, namely if the cleanup method can also throw an exception. A typical case is closing a stream. Suppose you want to make sure that you close a stream when an exception hits in the stream processing code.

Now suppose that the code in the try block throws some exception other than an IOException that is of interest to the caller of the code. The finally block executes, andthe close method is called. That method can itself throw an IOException! When it does,then the original exception is lost and the IOException is thrown instead. That is verymuch against the spirit of exception handling.

It is always a good idea unfortunately not one that the designers of the InputStream class chose to follow—to throw no exceptions in cleanup operations such as dispose, close, and so on, that you expect users to call in finally blocks.

Analyzing Stack Trace Elements

A stack trace is a listing of all pending method calls at a particular point in the execution of a program. You have almost certainly seen stack trace listings—they are displayed whenever a Java program terminates with an uncaught exception.

Before Java SE 1.4, you could access the text description of a stack trace by calling the printStack Trace method of the Throwable class. Now you can call the getStackTrace method to get an array of StackTraceElement objects that you can analyze in your program. For example:

The StackTraceElement class has methods to obtain the file name and line number, as well as the class and method name, of the executing line of code. The toString method yields a formatted string containing all of this information.

Java SE 5.0 added the static Thread.getAll StackTraces method that yields the stack traces of all threads. Here is how you use that method:

Listing below prints the stack trace of a recursive factorial function. For example, if you compute factorial(3), the printout is

java.lang.Throwable 1.0

  • Throwable(Throwable cause) 1.4
  • Throwable(String message, Throwable cause) 1.4 : constructs a Throwable with a given cause.
  • Throwable initCause(Throwable cause) 1.4 : sets the cause for this object or throws an exception if this object already has a cause. Returns this.
  • Throwable getCause() 1.4 : gets the exception object that was set as the cause for this object, or null if no cause was
  • set.StackTraceElement[] getStackTrace() 1.4: gets the trace of the call stack at the time this object was constructed.

java.lang.Exception 1.0

  • Exception(Throwable cause) 1.4
  • Exception(String message, Throwable cause)

constructs an Exception with a given cause.

java.lang.RuntimeException 1.0

  • RuntimeException(Throwable cause) 1.4
  • RuntimeException(String message, Throwable cause) 1.4

constructs a RuntimeException with a given cause.

java.lang.StackTraceElement 1.4

  • String getFileName()
    gets the name of the source file containing the execution point of this element, ornull if the information is not available.
  • int getLineNumber()
    gets the line number of the source file containing the execution point of this element, or –1 if the information is not available.
  • String getClassName()
    gets the fully qualified name of the class containing the execution point of this element.
  • String getMethodName()
    gets the name of the method containing the execution point of this element. The name of a constructor is <init>. The name of a static initializer is <clinit>. You can’t distinguish between overloaded methods with the same name.
  • boolean isNativeMethod()
    returns true if the execution point of this element is inside a native method.
  • String toString()
    returns a formatted string containing the class and method name and the file name and line number, if available.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics