import java.io.*; import java.util.*; /** * This is an example of how to handle checked exceptions. * * @author Stephanie Taylor */ public class Lecture11 { /** Read the first character of the given file and print it out * This version catches the checked exceptions and prints error messages. * * @param fn, name of file */ public static void doFileThing_catching( String fn ) { try { FileReader fr = new FileReader( fn ); char[] c = new char[1]; fr.read(c); System.out.println( "The first character is " + c[0] ); } catch (FileNotFoundException e) { System.out.println( "Give up, " + fn + " doesn't exist." ); } catch (IOException e) { System.out.println( "We had a hard time reading the first character from " + fn ); } } /** Read the first character of the given file and print it out * This version just passes along the checked exceptions. * * @param fn, name of file */ public static void doFileThing_specifying( String fn ) throws FileNotFoundException, IOException { FileReader fr = new FileReader( fn ); char[] c = new char[1]; fr.read(c); System.out.println( "The first character is " + c[0] ); } /** Test the doFileThing methods */ public static void main( String[] args ) { doFileThing_catching( "test.txt" ); try { doFileThing_specifying( "test.txt" ); } catch (java.lang.Exception e) { ; } } }