CS 46B - Lecture 6

Cover page image

Pre-class reading

If You Can't Do it By Hand...

HOWTO 11.1 - Processing Text Files

Lecture 6 Clicker Question 1

Have a look at Homework 4C.

We need to read two files with the same format.

That's an obvious case for a method that reads a file and returns the data in the file (boy and girl names).

What should it return?

  1. An array ArrayList<String>[] of length 2, holding a list of boy names and a list of girl names
  2. An array String[][] of String[] arrays of length 2, holding an array of boy names and an array of girl names
  3. An array list ArrayList<ArrayList<String>> of length 2, holding a list of boy names and a list of girl names
  4. An ArrayList<Person>, where Person is a class whose instances have a name and a gender

Throwing Exceptions

Hierarchy of Exception Classes

Lecture 6 Clicker Question 2

public static Comparable smallest(Comparable[] values)
   if (values.length == 0) throw new XXXException(); // What should we throw?
   Comparable smallestSoFar = values[0];
   for (int i = 1; i < values.length; i++)
      if (values[i].compareTo(smallestSoFar) < 0)
         smallestSoFar = values[i];
   return smallestSoFar;
  1. ArrayIndexOutOfBoundsException
  2. IllegalArgumentException
  3. IllegalStateException
  4. NoSuchElementException

Checked Exceptions

Lecture 6 Clicker Question 3

When you call a[i] on an array, your code might throw an ArrayIndexOutOfBoundsException. Why don't you have to tag methods with throws ArrayIndexOutOfBoundsException?

Catching Exceptions

   String filename = . . .;
   FileReader reader = new FileReader(filename);
   Scanner in = new Scanner(reader);
   String input = in.next();
   int value = Integer.parseInt(input);
   . . .
catch (IOException exception)
catch (NumberFormatException exception)
   System.out.println("Input was not a number");

Exceptions and Inheritance

Lecture 6 Clicker Question 4

catch (FileNotFoundException ex) { println("File not found"); }
catch (IOException ex) { println("I/O error"); }
catch (RuntimeException ex) { println("Something went wrong"); }

Suppose process throws a EOFException. What gets printed?


The finally Clause

The finally Clause

Scanner in = new Scanner(file);
finally {

Lecture 6 Clicker Question 5

public void read(String filename) 
   Scanner in = null; 
      in = new Scanner(new File(filename));
   catch (IOException ex) { println("I/O Error"); }
   finally { in.close(); }

Which of the following is true if the file does not exist?

  1. The message "I/O error" is printed
  2. A FileNotFoundException is thrown to the caller of read
  3. A NullPointerException is thrown to the caller of read
  4. The read method returns without printing anything and without an exception

The Try-With-Resources Statement

Designing with Exceptions

Before Next Class