August 2000
JP219 : JAVA PROGRAMMING

QUESTION 3

Total Marks: 15 Marks

Click here to access other questions

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

(a) State what is meant by an exception in a Java program, and give an example of a situation which might reasonably be expected to result in an exception. [2 marks]
(a) • An exception is a signal to indicate some abnormal condition, such as an error has occurred; (1 mark)
• An example might be dividing by zero, file not found, or any other suitable example; (1 mark)
[2 marks]

(b) Define a method, called Divide, which takes as parameters two doubles, x and y. The method should first ensure that y is non zero, returning the result of dividing x by y if it is not, and throwing the relevant ArithmeticException if it is. [5 marks]
(b) double Divide(doube x, double y)
throws ArithmeticException
{
  if(y== 0) {
  throw new ArithmeticException();
  } else {
  return x/y;
  }
}
• Including the throws clause in the method signature; (1 mark)
• testing for y==0; (1 mark)
• Creating a new ArithmeticException object if the error condition is true; (1 mark)
• Throwing it; (1 mark)
• Returning the value if there has been no error; (1 mark)
[5 marks]

(c) Define a method, called FooBar, which will call the method Divide with the parameters a and b. Should the calling of Divide result in an exception, FooBar should indicate this by printing out the appropriate error message. If the method has attempted to call Divide, it should also print out a message stating this, regardless of success or failure. [4 marks]
(c) void FooBar() {
double a, b;
try {
  Divide(a, b);
}
catch(Arithmeticexception a) {
  System.out.println("ArithmeticException caught!");
}
finally {
  System.out.println("The operation has terminated!");
  }
}
• try clause; (1 mark)
• catch clause; (1 mark)
• finally clause; (1 mark)
• Performing the correct action in each clause; (1 mark)
[4 marks]

(d) Declare an exception class called MyArithmeticException, which extends the standard ArithmeticException. The class should contain the member string Reason, and a constructor function which takes as a parameter a string, and initialises Reason appropriately. [4 marks]
(d) public class MyArithmeticException extends ArithMeticException {
  public String Reason;
  MyArithMeticException(String r) {
  Reason= new String(r);
  }
};
• Declaring the class to extend ArithmeticException; (1 mark)
• Including the string Reason; (1 mark)
• Constructor function; (1 mark)
• Allocating and initialising the Reason string; (1 mark)
[4 marks]