下面的代码计算存储在文本文件中的数字的平均值。我为“找不到文件”错误添加了一些异常处理。当文本文件中的数据不是数字(或整型)时,我需要知道如何添加另一个异常。我考虑添加多个捕获物。但是不确定是怎么做到的?
import java.util.*;
import java.io.*;
public class NumAvg2 {
    public static void main(String[] args)
    {
    int c = 1;  
    long sum = 0;
    String strFileName;
    strFileName = args[0];
    Scanner scFileData;
    try{
        scFileData = new Scanner (new File(strFileName));
        while (scFileData.hasNext())
        {
            sum = sum + scFileData.nextInt();
            c++;
        }
    scFileData.close();
    System.out.println("Number of integers: " + (c - 1)); 
    System.out.println( "Average = " + (float)sum/(c - 1));
    } catch (FileNotFoundException e) {
        System.out.println("File not found!");
        System.exit(1);
    }
  } 
}   发布于 2012-09-27 03:19:47
...
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
    System.exit(1);
} catch (InputMismatchException e) {
    // Add stuff into your new exception handling block
}
...您的集成开发环境可能没有抱怨过这一点,因为InputMismatchException是一个RuntimeException (未检查的异常),而FileNotFoundException是一个常规的检查异常。
https://stackoverflow.com/questions/12608828
复制相似问题