【问题标题】:Try and Catch Error in Java在 Java 中尝试并捕获错误
【发布时间】:2015-06-29 00:13:58
【问题描述】:

我需要编写一个程序来读取文本文件并计算不同的东西,但是,如果找不到文件名,它应该打印一条错误消息,其中包含来自 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();

除了打印不正确的错误信息外,我的程序运行良好。

任何/所有帮助将不胜感激!

【问题讨论】:

  • 找到文件但文件内容不是int
  • 那么我该如何更改它以仅打印 FileNotFound 异常??
  • 下面in为空时从方法返回、退出程序或以其他方式处理。如果操作失败,则无法获取下一个数字。
  • 无论如何,文件 is 已找到,但 not 包含一个“整数”作为第一个元素。如果它实际上抛出了 FNFE,那么 in 将为空。这就是 actual InputMistmatchException 的意思。

标签: java try-catch


【解决方案1】:

你在 in.nextInt() 行抛出异常,你试图读取一个整数,但扫描器发现了别的东西。如果您需要将所有这些都视为一个错误,您可以将它们放在同一个 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();
     }

【讨论】:

    【解决方案2】:

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

    这更简单:从这个开始。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      相关资源
      最近更新 更多