javaioexceptionbufferedreader

Readline in java compile time error


I know i'm doing something very wrong here, but I'll be frank here my knowledge of java is very weak. Whenever I call dataIn.readLine() I get this compile time error

unreported exception java.io.IOException; must be caught or declared to be thrown

Here's the code, I know the naming conventions are awful and that it nearly does nothing.

import java.io.*; 
public class money {
    public static void main( String[]args ){
        String quarters; 
        String dimes; 
        String nickels; 
        String pennies; 
        int iquarters; 
        int idimes;
        int inickels; 
        int ipennies; 
        BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); 

        System.out.println( "Enter the number of quarters. " ); 
        quarters = dataIn.readLine(); 
        System.out.println( "Enter the number of dimes" ); 
        dimes = dataIn.readLine(); 
        System.out.println( "Enter the number of nickels" ); 
        nickels = dataIn.readLine(); 
        System.out.println( "Enter the number of pennies" ); 
        pennies = dataIn.readLine(); 

        iquarters = Integer.parseInt( quarters ); 
        idimes = Integer.parseInt( dimes ); 
        inickels = Integer.parseInt( nickels ); 
        ipennies = Integer.parseInt( pennies ); 

    }
}

http://www.ideone.com/9OM6O Compiled it here as well with the same result.


Solution

  • readLine() can throw an IOException. You need to wrap it in a try-catch block that catches that exception if it arises, and then handles it in a way that's sane for what you're doing. Control will immediately flow out of the try block and into the catch block if an exception is thrown by readLine().

    try
    {
        dataIn.readLine();
        // ... etc
    }
    catch(IOException e)
    {
        // handle it. Display an error message to the user?
    }