Computer Science 225
Advanced Programming

Spring 2017, Siena College

CatchExample BlueJ Project

Click here to download a BlueJ project for CatchExample.


CatchExample Source Code

The Java source code for CatchExample is below. Click on a file name to download it.


CatchExample.java

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.
 *
 * Jim Teresco, Siena College, Computer Science 225, Spring 2017
 *
 * $Id: templateapp.java 2975 2016-08-30 02:35:29Z terescoj $
 */

public class CatchExample {

    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
        Scanner s = null;
        int value = 0;
        
        try {
            
            // this line might generate an ArrayIndexOutOfBoundsException, which is
            // intentionally not caught, but we will catch a possible
            // FileNotFoundException
            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);
        }
        // the finally clause will happen even if an exception was thrown
        finally {            
            if (s != null) s.close();
        }
        
        System.out.println("I found the number " + value + " in your file.");
    }
}