Objectives

In this lab, you will implement exception handling in ShopV5.0.

Objectives

On completion of this lab you should be able to:

  • Store objects into XML files and retrieve them from XML files (using ShopV4.0 as a starting point).

  • Apply this XML knowledge to another domain i.e. the DVD library.

  • Include Exception handling for invalid user input.

Developing Shop V5.0

In this practical, you will create a new project called ShopV5.0 in Eclipse and refactor the code so that exception handling is fully implemented for the user input.

Starting ShopV5.0

  • Create a new project called ShopV5.0 and copy the three java files and the jar component from ShopV4.0 into it.

  • The solution to the ShopV4.0 exercise is here should you need it.

Runtime Errors in ShopV5.0

  • Did you notice when you enter a non-number when you were expecting a double, that the following error happens:

Run time Exception

  • This line of code in the MenuController class caused the error:
double unitCost = input.nextDouble();
  • We are going to write code to handle these two errors:

Run time errors

  • Replace this code:

  • With this:

  • Test this new code. Does it work as expected e.g.

Developing Shop V5.0 (continued)

In the previous step, we wrote code to handle the read of the unit cost (double) and the product code (int).

However, there are other reads of int values in the MenuController class that we need to handle.

More int reads

This would require us re-writing the same code in multiple places. In order, to keep our code DRY, we will write a helper method to validate the int input.

Writing a method to validate int input

  • Make the following changes in MenuController i.e. a new helper method and a call to it:

Validate int method and a call to it

  • Make a second call to the new helper method, as shown here:

A second call to the helper method

Writing a method to validate double input

  • Make the following changes in MenuController i.e. another new helper method and a call to it:

Validate double method and a call to it

  • Test this new code. Does it work as expected for both int and double values?

Solutions

The solution to the ShopV5.0 exercise is here.