Handling Exceptions in Java
There are many reasons why programs can have errors at run time. In many cases, these could have been avoided if the programmer built proper checks into the program in the first place.
For example, bad input typed in by the user can cause all kinds of errors. If the program checked the user’s input to ensure that it is within an acceptable range before attempting to use it, this need not happen.
In other cases, the error can be caused by circumstances which cannot be avoided by the programmer. A file needed by the program may have been accidentally deleted by a user, or the system may have run out of memory.
In all cases of run-time errors, it is important to either deal with the error if possible, or shut the program down with a meaningful error message and minimum loss of data if the error cannot be dealt with.
In Java, if a method cannot complete normally, it “throws” an exception. The exception is an object containing details of the problem that occurred. The exception can then be “caught” by some other part of the program, known as an exception handler. This exception handler can do one of several things, for example:
- Fix the problem, if possible.
- Release resources, for example close files etc, and propagate the error back to the Java runtime environment so that the program is closed
- Display a meaningful error message, and allow program execution to continue.
The programmer must decide what type of action is appropriate for each type of exception.
If an exception is not “caught” within the method that threw it, it is propagated back to the method that called it. If it is not caught there, it is propagated back up the hierarchy until an exception handler is found, or, if none is provided, back to the Java runtime environment.
Java provides a hierarchy of exception classes, all of which originate from the superclass Throwable. Some of these can be thrown by the built-in Java classes. Some examples of the predefined exception classes are listed below. A full list is available in the Java documentation.
ClassNotFoundException
IllegalAccessException
IOException
EOFException
FileNotFoundException
MalformedURLException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException
These exception classes include data, such as an error message which can be set by the programmer, and several useful methods such as:
printStackTrace(), which prints a trace of where the error occurred, and the methods through which the program arrived at that point
getMessage(), which retrieves the error message contained in the exception object.
Many of the methods of the Java library classes throw exceptions if they encounter unexpected situations. The compiler won’t allow you to ignore these exceptions – you must do one of two things. You can either propagate the exception – in other words, pass it on for another method to deal with, or ‘catch’ it, and deal with it yourself. We’ll look at how this can be coded.
Propagating an exception: if you know that your method can throw an exception that it will not handle, the compiler must be informed by adding the clause throws exceptiontype to the end of the method header, where exceptiontype is the class of the exception object which is thrown.
For example, a method that processes a file is always prone to exceptions. The method header may be coded:
public void GetCustInfo(String Custno) throws IOException
Many of the methods in library classes do this, especially those that deal with file handling.
Any method that calls the GetCustInfo method must either catch the error or propagate it to the next level up. If it is to be propagated, then the calling method must also specify throws IOException in its own header.
Catching an Exception: This is done by enclosing the statements that may cause an error in a try … catch block, as follows:
try
{
catch (exceptionclass objectname)
{
The exception class in the catch block must be either the one thrown by the statements in the try block, or a superclass of it.
The statements in the catch block can use the methods associated with the object caught in order to retrieve information from it, for example:
catch(IOException badFile)
{
badFile.printStackTrace;
etc
When an error is detected in the try block, control is passed directly to the catch block, and all later statements in the try block are ignored.
The following example shows the Calculator program from a previous example modified to include exception handling, so that if an invalid number is entered on the command line, a user-friendly error message is displayed.
// ********************************************************
// * This program will carry out a calculation
// * entered on the command line. The calculation
// * should be entered as a number, followed by a
// * space, followed by an operand, followed by a
// * space and a number. Valid operands are +,-,x
// * and /.
// *********************************************************
public class calc
{
public static void main(String[] args) Op=args[1].charAt(0); //First character of second // ********************************************************* switch(Op)
{
char Op;
// *******************************************************
// Number format checking has now been included here
// *******************************************************
try
{
catch (NumberFormatException ex)
{
System.exit(0);
//argument is the operand
try
{
catch (NumberFormatException ex)
{
System.exit(0);
// Decide on the correct calculation depending on
// the operand entered
// **********************************************************
{
Ans=Num1+Num2;
break;
case '-':
Ans=Num1-Num2;
break;
case 'x':
Ans=Num1*Num2;
break;
case '/':
Ans=Num1/Num2;
break;
default:
System.out.println ("Can't do that - I'm only a cheap calculator");
break;
System.out.println("Answer is " + Ans);
}
Congratulations! You’ve now learned nearly all that you need to know to use the Java language. However, Java programmers never stop learning. This is because there are so many Java classes available for you to use in your programs.
You will need to get used to working with the Java documentation to find out how to use new classes. You can also find a lot of useful demonstation programs in the demo directory that is found underneath the directory in which Java was installed (In Windows, this is usually under c:\Program Files\java). You can also visit the tutorials at www.java.sun.com to learn more.
For the rest of this tutorial, we’ll have a quick look at some sample programs that use Java library classes for different types of applications.