java:unreported exception java.io.FileNotFoundException;必须被抓住或宣布被抛出

时间:2014-08-31 22:50:03

标签: java

为什么我会在此代码中收到“必须被捕获或声明被抛出”错误?我想要的是通过将它粘贴到一个新的java程序中来测试一堆代码,这是一堆代码最简单的方法吗?

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt"));
        List<String> symbolList = new ArrayList<String>();
        while (sc.hasNextLine()) {
            symbolList.add(sc.nextLine());
        }

        PrintWriter logput = new PrintWriter("C:\\Users\\User\\Selenium\\scrapjv\\interface\\log.txt", "UTF-8");
        for (String symb : symbolList) {
            System.out.println(symb);
        }
        logput.close();
    }
}

2 个答案:

答案 0 :(得分:2)

如果找不到该文件,您调用的某些方法可能会抛出FileNotFoundException

 public Scanner(File source) throws FileNotFoundException
 public PrintWriter(String fileName) throws FileNotFoundException

Java的编译器会检查一些抛出的异常 - 除RuntimeException及其子类之外的异常 - 被捕获或声明抛出。否则编译将失败。这有助于在程序运行之前在编译时发现一些错误。

一个选项是声明你的调用函数抛出异常或超类:

 public static void main(String[] args) throws FileNotFoundException {

在这种情况下,更好的选择是捕获异常并对其执行某些操作。例如,以下是如何为Scanner()异常执行此操作:

    File inFile = new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt");
    try {
        Scanner sc = new Scanner( inFile );
        List<String> symbolList = new ArrayList<String>();
        while (sc.hasNextLine()) {
            symbolList.add(sc.nextLine());
        }
    }
    catch ( FileNotFoundException e ) {
        System.out.println("Could not find file: " + inFile.getAbsolutePath());
    }

答案 1 :(得分:1)

您的两个Scanner声明行有机会抛出异常,这些异常基本上是代码执行后发生的错误(因此有时称为运行时错误)。由于编译器知道您的代码可能会发生FileNotFoundException,因此需要catch例外。

这是通过将代码包含在try-catch块中来完成的。

try {

    Scanner sc = new Scanner(new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt"));
    List<String> symbolList = new ArrayList<String>();
    while (sc.hasNextLine()) {
        symbolList.add(sc.nextLine());
    }


    PrintWriter logput = new PrintWriter("C:\\Users\\User\\Selenium\\scrapjv\\interface\\log.txt", "UTF-8");
    for (String symb : symbolList) {
        System.out.println(symb);
    }
    logput.close();


} catch (java.io.FileNotFoundException ex)
{
    ex.printStackTrace();
}