Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Exceptions

Exception handling is a useful and powerful technique but it is not expected ina dossier and will not be tested in examinations.

 

 

 

 

 

 

 

 

 

 

 

 

It's good practice to document the exception.

Add the throws commen.

 

 

Test for denominator zero

Construct the new FractionException instance.

 

 

All Custom made Exception Classes extend the built-in Exception Class.

 

 

The call to super() invokes the Constructor of the super (parent) Class.

 

HL candidates find out more about inheritance in topic 5.

Sl Candidates can take it on trust or not bother with exceptions at all.

 

 

 

The runtime system is the "sandbox" within which our Java Applets play.

It can be difficult to work out exactly where the best place to catch an exception is.

Any block of code that could throw an exception is put in the try block .

If the exception occurs in any line, control passes immediately to the catch block .

Here we simply display the message in the TextField.

This is what it looks like when running in BlueJ.

 

BlueJ's representation of the relationship between the classes.

 

 

 

 

 

 

 

Test the Applet with an illegal fraction, go on, you know you want to.

HL mastery aspect inheritance

The next section takes a quick look at inheritance.

  On this page : [ Errors in Classes | Throwing Exceptions | Trying and Catching ]

  Related links:      [ terminology | intro to Java Classes | more about Classes ]

When is a Fraction not a Fraction?

A simple example might be 1/0. An error condition in the Fraction Class might arise following an internal calculation or when another programmer or application using the Class attempts to Construct an "illegal" fraction.

If you try to use the TestFraction Apple t to add 1/0 to 4/5 you will get the answer 5/0.

It is possible for the Fraction Class to ignore this error but usually you would want to signal that the condition has occurred. One simple way is to have the Fraction Class output a message.

However, how and where will this message be output,? Via the console, via a TextField? How will the application using th Fraction Class know where to find the message?

Throwing an exception

Exceptions are a way for the Fraction Class to signal that an error has occured and provide a message without otherwise affecting the operation of the application. A method can construct an object of an Exception Class and associate an error message by using a throw statement.

For example if our Fraction Constructor (we have created a new class called NewFraction) is passed a zero denominator:

/**
* Construct a fraction given two ints (numerator first)
*
* @param n the numerator
* @param d the denominator
* @throws FractionException if the denominator is zero
*/
public NewFraction(int n, int d) throws FractionException
{
   if (d != 0)
   {
     setNumerator(n);
     setDenominator(d);
   }
   else
   {
     throw new FractionException("Denominator can't be zero");
   }
}

This won't compile until we actually create the FractionException Class:

/**
* Handles exceptions in the Fraction Class
*
* @author Mr J
* @version 20040218
*/

public class FractionException extends Exception
{
   public FractionException()
   {
     super();
   }
   public FractionException(String message)
   {
     super(message);
   }
}

Any methods that use the constructor must also throw (or catch as we shall see next) the exception :

public static NewFraction add(NewFraction a, NewFraction b)
                                                   throws FractionException

Catching an exception

The TestNewFraction Applet is used to test the working of our new exception mechanism.

When a method that can throw an exception is called, the Application can throw the exception again , in which case the runtime system will deal with it by giving an error message.

Better still, since this application has control over how the data gets to the NewFraction Class it can deal with it by using a try catch block.

public void actionPerformed(ActionEvent e)
{
   // Get the data from the boxes and make the fraction objects
   try
   {
     NewFraction a = new NewFraction( Integer.parseInt(n1.getText()),
     Integer.parseInt(d1.getText()) );
     NewFraction b = new NewFraction( Integer.parseInt(n2.getText()),
     Integer.parseInt(d2.getText()) );
     // add them together
     NewFraction c = NewFraction.add( a, b );
     greeting.setText("" + c.toString());
   }
   catch( FractionException fe)
   {
     greeting.setText(fe.getMessage());
   }
}

Here is the example Applet, followed by the code for NewFraction, FractionException and TestNewFraction:

 

Codes for TestNewFraction.java , NewFraction.java and FractionException.java .

Related: [ Java Home | previous: Classes | next:Inheritance]

 


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009