Java异常处理?

FAU*_*HID 3 java exception-handling exception try-catch

以下代码计算存储在文本文件中的数字的平均值.我为"找不到文件"错误添加了一些异常处理.我需要知道如何在文本文件中的数据不是数字(或非int)时添加另一个异常.我考虑过添加多个捕获量.不知道怎么样?

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

  } 
}   
Run Code Online (Sandbox Code Playgroud)

RNJ*_*RNJ 6

您可以使用Java 7的多捕捉,如果你想

try {
...
}
catch (FileNotFoundException|InputMismatchException ex) {
//deal with exception
}
Run Code Online (Sandbox Code Playgroud)

这比多次捕获更清洁.如果抛出这些异常中的任何一个,则会在单个catch块中捕获它们