错误:未报告的异常FileNotFoundException;必须被抓住或宣布被抛出 [英] error: unreported exception FileNotFoundException; must be caught or declared to be thrown

查看:186
本文介绍了错误:未报告的异常FileNotFoundException;必须被抓住或宣布被抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个将字符串输出到文本文件的简单程序。使用我在这里找到的代码,我将以下代码放在一起:

I'm trying to create a simple program that will output a string to a text file. Using code I found here, I have put together the following code:

import java.io.*;

public class Testing {

  public static void main(String[] args) {

    File file = new File ("file.txt");
    file.getParentFile().mkdirs();

    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close();       
  }
} 

J-grip引发了以下错误:

J-grasp throws me the following error:

 ----jGRASP exec: javac -g Testing.java

Testing.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    PrintWriter printWriter = new PrintWriter(file);
                              ^
1 error

 ----jGRASP wedge2: exit code for process is 1.

由于我对Java很新,我不知道这意味着什么。任何人都能指出我正确的方向吗?

Since I'm pretty new to Java, I have no idea what this means. Can anybody point me in the right direction?

推荐答案

您没有告诉编译器有可能抛出 FileNotFoundException
a 如果文件不存在,将抛出FileNotFoundException

You are not telling the compiler that there is a chance to throw a FileNotFoundException a FileNotFoundException will be thrown if the file does not exist.

试试这个

public static void main(String[] args) throws FileNotFoundException {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    try
    {
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close();       
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
    }
}

这篇关于错误:未报告的异常FileNotFoundException;必须被抓住或宣布被抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆