From C to Java: an introduction to Java for C programmers

(Continued from our introduction to Java for C programmers.)

Error handling in Java and C

In C, there are three common ways of handling errors:

Java, like some other modern languages, uses a different mechanism called exceptions to deal with error cases. A method is declared with the types of exception or error conditions that it is likely to produce:

public void operateOnFile(File f) throws IOException {
  ...
}

Then, when we call this method, we put a block to catch the exception if it is "thrown" by the method:

try {
  operateOnFile(f);
} catch (IOException ioe) {
  warnUser("An error occurred: " + ioe.getMessage());
}

Exceptions are more convenient than checking for an error condition after every function call (in effect, the JVM does the checking for us). And in chains of method calls, they allow for the option of "passing the exception up" to the caller. For example, we can write:

public void processFiles(File[] files) throws IOException {
  for (File f : files) {
    operateOnFile(f);
  }
}

The above method takes an array of files and in turn calls operateOnFile() on them. Any one of the calls to operateOnFile() could throw an IOException if an I/O error occurs processing the file. But inside our processFiles() method, we don't deal with the exception there and then. We "throw it up" to the caller of our method, who must either deal with it or throw it up again etc.

In this way, we are relieved of the task of "micro-managing" error conditions, which often occurs in C programming as we have to tediously check for an error after every single library call.

There are also a number of so-called runtime exceptions, such as a NullPointerException (a misnomer for when we try to access fields or methods of a null object reference). These are exceptions that we essentially don't expect to occur and don't need to explicitly catch. (A system default exception handler will deal with them.)

On the next page, we discuss the standard Java class libraries.