CS 46B - Lecture 6

Cover page image

Pre-class reading

Checked Exceptions

Lecture 6 Clicker Question 1

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

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

Exceptions and Inheritance

Lecture 6 Clicker Question 2

try 
{
   process(filename)
}
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);
try
{
   readData(in);
}
finally
{
   in.close(); 
}

Lecture 6 Clicker Question 3

public void read(String filename) 
{
   Scanner in = null; 
   try
   {
      in = new Scanner(new File(filename));
      process(in);
   }
   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