Personal tools
You are here: Home Information Systems Java Platform Introduction 19. Exceptions

19. Exceptions

Document Actions
  • Send this
  • Print this
  • Content View
  • Bookmarks

Exceptions

<-- Previous

Table of Contents

Next -->

As you will all be aware by now, errors occur in programs - sometimes even in the simplest of programs. These errors will occur whether we wish it or not; it's almost impossible to produce an application that is completely error-free under all circumstances. The important thing to consider, is what happens after an error occurs? How will the error be handled, and which part of the code will handle it? Will the application be able to recover, or will it terminate?

The Java language uses exceptions to provide error-handling capabilities for its programs. An exception (short for exceptional event) is an event that occurs during the execution of a program, that disrupts the normal flow of instructions. It's probable that by now you have encountered at least one exception while compiling or running your applications. If your code doesn't deal with an exception, the Java interpreter will return an error message to the console when that exception occurs, and most often your application will terminate - stop running. When an exception occurs, the code is said to have thrown an exception. Exceptions in Java are objects - you can inspect exception classes in the Java documentation; look at the java.lang classes for example.

There are two kinds of exceptions that we need to consider - checked exceptions and run-time exceptions

Checked exceptions

The Java compiler checks the classes we are using in our code to see if any of them admit that they throw exceptions, have methods that throw exceptions, or if any of them make use of other classes (such as the intrinsic Java classes) that throw exceptions. In the image below, we see the instance method java.lang.InputStream.read() as described in the Java documentation. Notice that the method admits that it throws an IOException (Input/Output Exception). If we make use of an InputStream object, and our class doesn't admit that an IOException might occur as a result of using this class and its methods, the Java compiler will complain and refuse to compile our code.

We had just such an instance in our ConsoleCylinder class - we had to adjust the class definition to admit that an exception could occur:

public class ConsoleCylinder {
   public static void main(String[] args) 
			throws IOException {
       ...
   }
}

We didn't write any code to handle any exception that might have been thrown, which was why we had to admit that an exception could be thrown. The reason for this is that if an exception occurs, Java looks for an exception handler in the class in which it occurred - if it doesn't find one, it passes the buck up the code hierarchy until it finds an appropriate exception handler. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates. If an appropriate handler is found and engaged, the handler is said to catch the exception.

What this all means is that if our code throws a checked exception, we must either deal with it by writing an exception handler, or we must admit that an exception might be thrown and pass the problem up the stack.

There are three advantages to the way in which Java deals with errors:

  1. Error handling code can be kept completely separate from 'regular' code.
  2. Errors can be sent up the stack until an error-handler is found.
  3. Error types can be grouped, and proper differentiation between error types can be maintained.

Run-time exceptions

There is a very large group of exceptions that the compiler cannot check for; these are exceptions that occur during run-time as the result of an unexpected condition, or a logic error. For example, imagine that we are expecting the user to enter an integer value into a dialog box, and the user actually enters a decimal fraction - what will happen? If we have written code to deal with just such an event, no problem; if we haven't... The compiler cannot check for this kind of problem because it cannot make any decision about the logic we have followed in our code, nor can it predict the actions of users.

Consider our class DialogCylinder - here is the code for you again below:

import javax.swing.JOptionPane;

/**
* Tests using the Cylinder class, and supplying it with 
* constructor arguments from an input dialog box.
*/
public class DialogCylinder {
   public static void main(String[] args) {
      
      double rad = Double.parseDouble(JOptionPane.showInputDialog(
      "Enter the radius of the Cylinder:"));
      double ht = Double.parseDouble(JOptionPane.showInputDialog(
      "Enter the height of the Cylinder:"));
      Cylinder myCylinder = new Cylinder(rad, ht);
      System.out.println("\nThe volume of the cylinder is: " + 
      myCylinder.getVolume());
	  
      System.exit(0);
	  
   }
}

This is precisely a case in point - what if the user enters a string into one of the dialog boxes instead of a number? We have provided no exception handlers in our code to deal with this situation, and the image below shows what happens:

 

There is a further complication here - because we are using a dialog box and code execution was stopped before the line

System.exit(0);

was executed, in some versions of Java before 1.5.0 execution hangs without returning execution to the console! (In later versions, there is a pause before the Java VM manages to clean up after the exception and return execution to the console - still not ideal.) We as programmers realise that we can solve this by typing Ctrl C, but will the users? Clearly, this is a very easy mistake to make as the user might simply have typed inaccurately and struck a character key and number key at the same time, pressing Enter too quickly to see and fix the mistake. We can place code in main to deal with the problem by designing the code to force the user to enter a number. Alternatively we can stop this happening by handling the NumberFormatException that is being thrown by the wrong kind of data being submitted to our code.

<-- Previous

Table of Contents

Next -->

Copyright 2007-2008, by the Contributing Authors. Cite/attribute Resource. 19. Exceptions. (2008, July 16). Retrieved May 21, 2013, from UWC Free Courseware Web site: http://free.uwc.ac.za/freecourseware/information-systems/java-platform-introduction/exceptions. This work is licensed under a Creative Commons License : Attribution-ShareAlike 3.0. Creative Commons License : Attribution-ShareAlike 3.0