Computer Science 225
Advanced Programming
Spring 2017, Siena College
CatchExampleWithResources BlueJ Project
Click here to download a BlueJ project for CatchExampleWithResources.
CatchExampleWithResources Source Code
The Java source code for CatchExampleWithResources is below. Click on a file name to download it.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Scanner;
/*
* Example CatchExample: an example demonstrating catch blocks, similar
* to code in Horstmann's Big Java, this one with a try with
* resources instead.
*
* Jim Teresco, Siena College, Computer Science 225, Spring 2017
*
* $Id: templateapp.java 2975 2016-08-30 02:35:29Z terescoj $
*/
public class CatchExampleWithResources {
public static void main(String[] args) {
// let's try to open a file and read in a string then convert it to an int,
// stored in this variable
int value = 0;
try(Scanner s = new Scanner(new File(args[0]))) {
// this line might generate a NoSuchElementException
String word = s.next();
// this line might generate a NumberFormatException
value = Integer.parseInt(word);
}
catch (FileNotFoundException e) {
// if our file is not found, we'll call this exception handler,
// with the appropriate message as encapsulated in the exception
System.err.println(e.getMessage());
System.err.println("Please try again, but with a file that exists next time.");
System.exit(1);
}
catch (IOException e) {
System.err.println(e.getMessage());
System.err.println("Your file existed, but some other IOException happened...");
System.exit(1);
}
catch (NoSuchElementException e) {
System.err.println("I expected your file to have something in it...");
System.exit(1);
}
catch (NumberFormatException e) {
System.err.println("I expected your file to have an int in it...");
System.exit(1);
}
System.out.println("I found the number " + value + " in your file.");
}
}