Exceptions and Errors

11.4 - 11.6

Exceptions and Errors

Problems that arise in you code during execution

Exceptions

Exceptions come in two types

Throwable Heirarchy

throwable heirarchy

Checked Exceptions must be handled

Handling Exceptions

Catching a Runtime Exception

You can also catch Runtime exceptions

Class Question #1

Suppose the process method throws a EOFException. What gets printed?

try 
{
   process(filename)
}
catch (FileNotFoundException ex) 
{ 
   System.out.println("File not found");  //a
}
catch (IOException ex) 
{
   System.out.println("I/O error");  //b
}
catch (RuntimeException ex)
{ 
   System.out.println("Something went wrong"); //c
}

The finally Clause



The finally Clause

Scanner in = new Scanner(reader);
try
{
   readData(in);
}
finally
{
   in.close(); 
}


Java 7 Shortcut

try (Scanner in = new Scanner(file))
{   
   readData(in);
} // in.close called automatically—Scanner is AutoCloseable

Class Question #2

public void read(String filename) 
{
   Scanner in = null; //why asign a null value?
   try
   {
      in = new Scanner(new File(filename));
      process(in);
   }
   catch (IOException ex) { System.out.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

Where to handle an exception

Process of exception handling is a search for a competent handler