简体   繁体   中英

Try and Catch Error in Java

I need to write a program that reads a text file and calculates different things, however, if the file name is not found, it should print an error message with the following error message from a try and catch block:

java.io.FileNotFoundException: inputValues (The system cannot find the file specfied)
    .......

However, I am instead receiving this error message:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:50)

Here is part of my code:

Scanner console = new Scanner(System.in);                   
        System.out.print("Please enter the name of the input file: ");                              // Prompts User to Enter Input File Name
        String inputFileName = console.nextLine();                                                  // Reads Input File Name

        Scanner in=null;                                                                            // 

        try
            {
                in = new Scanner(new File(inputFileName));                                          // Construct a Scanner Object
            }
        catch (IOException e)                                                                       // Exception was Thrown
            {
                System.out.print("FileNotFound Exception was caught, the program will exit.");      // Error Message Printed because of Exception
                e.printStackTrace();
            }

        int n = in.nextInt();                                                                       // Reads Number of Line in Data Set from First Line of Text Document
        double[] array = new double[n];                                                             // Declares Array with n Rows

Line 50 is: int n = in.nextInt();

Other than printing the incorrect error message, my program runs perfectly fine.

Any/all help would be greatly appreciated!

Your exception thrown at the line in.nextInt() where you are trying to read an integer but the scanner found something else. If you need to take all of them as a single error you can put them in the same try catch block as follows.

Scanner in=null;                                                                            // 

    try
    {
        in = new Scanner(new File(inputFileName));   
        // Construct a Scanner Object
        int n = in.nextInt();                                                                         

        // Reads Number of Line in Data Set from First Line of Text Document
        double[] array = new double[n];
    } catch (IOException e)                                                                           
    // Exception was Thrown
    {
        System.out.print("FileNotFound Exception was caught, the program will exit.");      
        // Error Message Printed because of Exception
        e.printStackTrace();
     } catch (InputMismatchException e)                                                                         
     // Exception was Thrown
     {
        System.out.print("Integer not found at the beginning of the file, the program will exit.");      
        // Error Message Printed because of Exception
        e.printStackTrace();
     }

Ugly, badly formatted code is hard to read and understand. It's part of why you're having trouble.

This is simpler: start with this.

package cruft;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * MessyFileDemo
 * @author Michael
 * @link https://stackoverflow.com/questions/31106118/try-and-catch-error-in-java
 * @since 6/28/2015 8:20 PM
 */
public class MessyFileDemo {

    public static void main(String[] args) {
        List<Double> values;
        InputStream is = null;
        try {
            String inputFilePath = args[0];
            is = new FileInputStream(inputFilePath);
            values = readValues(is);
            System.out.println(values);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(is);
        }
    }

    private static void close(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<Double> readValues(InputStream is) throws IOException {
        List<Double> values = new ArrayList<>();
        if (is != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                String [] tokens = line.split(",");
                for (String token : tokens) {
                    values.add(Double.parseDouble(token));
                }
            }
        }
        return values;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM