简体   繁体   English

尝试并捕获Java中的错误

[英]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: 我需要编写一个程序来读取文本文件并计算不同的内容,但是,如果找不到文件名,则它应从try and catch块中打印一条错误消息,并显示以下错误消息:

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(); 第50行是: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. 您的异常抛出在您尝试读取整数的in.nextInt()行中,但扫描程序发现了其他错误。 If you need to take all of them as a single error you can put them in the same try catch block as follows. 如果需要将所有这些都当作一个错误,可以将它们放在相同的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();
     }

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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