Lab 7: Exception Handling | Object Oriented Programming | CS 201, Lab Reports of Computer Science

Material Type: Lab; Class: Intro Obj Orient Programming; Subject: Computer Science; University: University of Alabama - Birmingham; Term: Unknown 2008;

Typology: Lab Reports

Pre 2010

Uploaded on 04/12/2010

koofers-user-gno-1
koofers-user-gno-1 🇺🇸

10 documents

1 / 3

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Part 2: Exception Handling
In this exercise you will:
1. Learn how to catch and handle exceptions.
pf3

Partial preview of the text

Download Lab 7: Exception Handling | Object Oriented Programming | CS 201 and more Lab Reports Computer Science in PDF only on Docsity!

Part 2: Exception Handling

In this exercise you will:

  1. Learn how to catch and handle exceptions.

Experiment 7.

File ScanInts.java is a program that contains a do while loop that does the following:

  • Read in a string.
  • If the length of the string is > 0, convert the string to an integer using Integer.parseInt.
  • Add the integer to sum.

After the user enters an empty string as input, the loop stops and the program displays the sum of the integers.

Step 1. Compile and run ScanInts.java. If you give it the input

10 20 30 40

it should print

The sum of the integers is 100.

Try some other inputs as well.

Step 2. Now try a line that contains both integers and a non-numeric value such as

10 2 xyz

You should get a NumberFormatException when the program tries to call Integer.parseInt on "xyz". One way around this is to put the do while loop inside a try, and catch the NumberFormatException but not do anything with it. This way if it is not an integer it does not cause an error; it goes to the exception handler, which does nothing.

Step 3. Modify the program to add a try statement that encompasses the entire do while loop. The try and opening { should go before the do and the } after the while. Catch a NumberFormatException, and have an empty body for the catch.

Step 4. Compile and run the program, and enter some integers and then a non-numeric value. You should find that it stops at the first non-integer. However the problem is that since the entire loop is inside the try, when an exception is thrown the loop is terminated.