Previous
Index

Next


Objective 4, When Exceptions occur

Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination).

Comment on this objective

This objective is asking you to understand the difference between checked and unchecked exceptions (ones you have to write code to catch and ones you dont), and to understand how the finally clause works.

Checked and Unchecked Exceptions

Although it is convenient that Java insists you insert code to trap exceptions where they are likely to occur such as during I/O it would be inconvenient if you had to insert such code where the programmer ought to have control over the program state. An example of this is the process of walking through each element of an array. One of the beauties of Java is the way it will specifically report this type of exception without any programmer intervention. This automatic exception handling is made possible by dividing the exceptions into Checked and Unchecked. Conditions such as the environment exhausting available ram or walking off the end of an array are looked after automatically whereas an attempt to open a non existent file require explicit try/catch exception handling.

Default Unchecked messages

The default consequence of an exception occuring for an unchecked excption is that a message will be sent to the console. For an example of this see the following code.

public class GetArg{
    public static void main(String argv[]){
        System.out.println(argv[0]);
    }

If compile this code and run it with no command line parameter you will get an error on the console saying something like

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
        at GetArg.main(GetArg.java:3)

Whilst this behaviour is acceptable for toy programs created for the purpose of learning, in real programs the user will probably not have access to the console and would not understand a message like this anyway. It is a standard practice to create code to check for the values that might cause an unchecked exception to be thrown. Thus that code might be modified to read.

public class GetArg{
    public static void main(String argv[]){
        if(argv.length ==0){
        System.out.println("Usage: GetArg param");
        }else{
        System.out.println(argv[0]);
        }
    }
}
       

Checked Exceptions

The programmer is required to write code to deal with checked exceptions. If there is no code to deal with the the checked exceptions that might occur it will not compile. As covered previously this code takes the form of a try/catch block, but it is possible to write an empty catch block that does nothing when an Exception occurs. This is of course not generally a good plan, as you have gone to the trouble to create code in the event of an excption occuring you may as well do something useful in that code. The two common things to do in the catch block are to generate an error message and/or to print a stack trace. The Exception system provides a very convenient way of generating a generally meaningful error message through its getMessage method.

Take a look at the following code.

import java.io.*;
public class FileOut{
    public static void main(String argv[]){
    try{
    FileReader fr = new FileReader("FileOut.txt");
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
    }
}

if you compile and run this code in a directory that does not have a file called FileOut.txt in it you will get an error message that says something like

FileOut.txt (No such file or directory)
       



The finally clause

The one oddity that you are likely to be questioned on in the exam, is under what circumstances the finally clause of a try/catch block is executed. The short answer to this is that the finally clause is almost always executed, even when you might think it would not be. Having said that, the path of execution of the try/catch/finally statements is something you really need to play with to convince yourself of what happens under what circumstances.

The finally clause of a try catch block will always execute, even if there are any return statements in the try catch part



One of the few occasions when the finally clause will not be executed is if there is a call to 

System.exit(0);

The exam tends not to attempt to catch you out with this exception to the rule.

The exam is more likely to give examples that include return statements in order to mislead you into thinking that the code will return without running the finally statement. Do not be mislead, the finally clause will almost always run. 

The try/catch clause must trap errors in the order their natural order of hierarchy. Thus you cannot attempt to trap the generic catch all Exception before you have put in a trap for the more specific IOException.

The following code will not compile

try{
    DataInputStream dis = new DataInputStream(System.in); 
    dis.read(); 
    }catch (Exception ioe) {} 
    catch (IOException e) {//Compile time error cause} 
    finally{}

This code will give an error message at compile time that the more specific IOException will never be reached. 




Questions

Question 1)

Which of the following will require the creaion of a try/catch block or rethrowing of any exception?

1) Opening and reading through a file
2) Accessing each element of an array of int values
3) Accessing each element of an array of Objectts
4) Calling a method defined with a throws clause

Question 2)

What will happen when you attempt to compile and run the following code?

import java.io.*;
class Base{
public static void amethod()throws FileNotFoundException{}
}



public class ExcepDemo extends Base{
public static void main(String argv[]){
       ExcepDemo e = new ExcepDemo();
}

public boolean amethod(int i){
 try{
    DataInputStream din = new DataInputStream(System.in);
    System.out.println("Pausing");
    din.readChar();
    System.out.println("Continuing");
    this.amethod();
    return true;
    }catch(IOException ioe) {}
    finally{
    System.out.println("Doing finally");
    }
    return false;
  }

  ExcepDemo(){
      amethod(99);
  }
}



1) Compile time error amethod does not throw FileNotFoundException
2) Compile, run and output of Pausing and Continuing
3) Compile, run and output of Pausing, Continuing, Doing Finally
4) Compile time error finally clause never reached



Answer to Question 1

Opening and reading through a file
4) Calling a method defined with a throws clather Resources on this topic

The type of elements of an array do not have any influence on exception handling. By definition the use of the throws clause in a method means it may throw an exception and thus that exception type must be causght (or rethrown) by code that uses it.

Answer to Question 2


3) Compile, run and output of Pausing, Continuing, Doing Finally

The finally clause will always be run.




Other sources on this topic

The Java Language Specification
http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44044



Previous
Index

Next