在Java中尝试和捕获错误

时间:2015-06-29 00:13:59

标签: java try-catch

我需要编写一个读取文本文件并计算不同内容的程序,但是,如果找不到文件名,它应该打印一条错误消息,其中包含来自try和catch块的以下错误消息:

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

但是,我收到此错误消息:

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)

以下是我的代码的一部分:

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

第50行是:int n = in.nextInt();

除了打印错误的错误信息之外,我的程序运行得非常好。

非常感谢任何/所有帮助!

2 个答案:

答案 0 :(得分:0)

您在异常行(.inxtInt()中抛出异常,您尝试读取整数,但扫描程序找到了其他内容。如果您需要将所有这些作为单个错误,您可以将它们放在相同的try catch块中,如下所示。

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();
     }

答案 1 :(得分:0)

丑陋,格式错误的代码难以阅读和理解。这是你遇到麻烦的部分原因。

这更简单:从此开始。

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;
    }

}