【问题标题】:java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown [duplicate]java: 未报告的异常 java.io.FileNotFoundException;必须被抓住或宣布被抛出[重复]
【发布时间】:2014-08-31 22:50:03
【问题描述】:

为什么我收到此代码的“必须被捕获或声明为被抛出”错误?我想要的只是通过将一堆代码粘贴到一个新的 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();
    }
}

【问题讨论】:

标签: java


【解决方案1】:

如果找不到文件,您调用的某些方法可能会抛出 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());
    }

【讨论】:

【解决方案2】:

你的两个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();
}

【讨论】:

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