August 1999
JP219 : JAVA PROGRAMMING

QUESTION 3

Total Marks: 20 Marks

Click here to access other questions

SUGGESTED SOLUTIONS
Solutions and allocated marks are indicated in green.
Return to
Question 3

(a) Define what is meant by the term exception with reference to the Java programming language. [2]
An exception is
  • a mild error condition
  • which disturbs the normal flow of execution of a program.

 

(b) Give two examples of abnormal conditions which may disturb the normal flow of program execution. [2]
Examples of abnormal conditions are :
  • The program attempts to open a file which does not exist;
  • The network connection is disrupted;
  • Operands are out of prescribed ranges;
  • Attempting to load a missing class files.

 

(c) State the purpose of an exception class. [2]
An exception class
  • defines mild error conditions that the program may encounter;
  • and how the program should deal with them.

 

(d) State the purpose of an error class. [2]
An Error class
  • defines more serious error conditions;
  • which the program should not usually attempt to recover from.

 

(e) Consider the following Java class definition :

public class OutOfRange extends Exception {
   private String reason;
   public OutOfRange(String reason) {
   this. reason = reason ;
}

public String GetReason() {
   return reason ;
  }

}

(i) Give the definition of a Java class, called MyClass which will contain a constructor function taking two integer parameters a and b, and a String returning function Foo, which is capable of throwing an exception of type OutOfRange.

(ii) Using the Java keyword throw, define the member function Foo such that it will throw the exception OutOfRange if and only if param is equal to or greater than limit, with the string message "parameter out of range".

(iii) Using the keyword try and catch, implement the constructor function such that it will try to ensure a is b, and will catch the exception, printing out the reason if it is not.

 

 

 

 

 

 

[4]

 


[4]

 

[4]

(i) A sample definition of MyClass follows:

public class MyClass {
    MyClass (int a, int b);
    Foo (int param, int limit) throws OutOfBounds;
}

 

(ii) A sample definition of Foo follows:

public Foo (int param, int limit) throws OutOfBounds {
   if (param >= limit)
      throw new OutOfBounds (' 'parameter out of range' ');
}

 

(iii) A sample definition of MyClass follows:

public MyClass (int a, int b) {
   try{
     Foo(a,b);
    }  catch (OutOfBounds E)  {
        System.out.printIn (E.getReason( ) );
    }
}