为什么我会收到“未处理的异常类型IOException”?

46

我有以下简单代码:

import java.io.*;
class IO {
    public static void main(String[] args) {    
       BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));    
       String userInput;    
       while ((userInput = stdIn.readLine()) != null) {
          System.out.println(userInput);
       }
    }
}

我得到了以下错误消息:

----------
1. ERROR in io.java (at line 10)
    while ((userInput = stdIn.readLine()) != null) {
                        ^^^^^^^^^^^^^^^^
Unhandled exception type IOException
----------
1 problem (1 error)roman@roman-laptop:~/work/java$ mcedit io.java 

有人知道为什么吗?我刚试图简化了该网站上给出的代码(此处)。我是不是简化过度了?

6个回答

74

您应该在主方法中添加 "throws IOException":

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

您可以在JLS中了解更多有关Java特定的已检查异常。


53

Java有一个叫做“检查异常”的特性。这意味着有某些种类的异常,它们是Exception的子类但不是RuntimeException的子类,如果一个方法可能会抛出这些异常,那么它必须在throws声明中列出它们,例如:void readData() throws IOException. IOException就是其中之一。

因此,当你调用一个在其throws声明中列出IOException的方法时,你必须在自己的throws声明中列出它或捕获它。

存在检查异常的理由是,对于某些类型的异常,你不能忽略它们发生的事实,因为它们的发生是一个相当常见的情况,而不是程序错误。所以编译器帮助你不要忘记可能会出现这种异常,并要求你以某种方式处理它们。

然而,并不是所有Java标准库中的检查异常类都符合这个理由,但这是一个完全不同的话题。


15

使用以下代码片段重试:

import java.io.*;

class IO {
    public static void main(String[] args) {    
        try {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));    
            String userInput;    
            while ((userInput = stdIn.readLine()) != null) {
                System.out.println(userInput);
            }
        } catch(IOException ie) {
            ie.printStackTrace();
        }   
    }
}

使用try-catch-finally比使用throws更好。当你使用try-catch-finally时,查找错误和调试会更容易。


0
将 "throws IOException" 添加到你的方法中,就像这样:
public static void main(String args[]) throws  IOException{

        FileReader reader=new FileReader("db.properties");

        Properties p=new Properties();
        p.load(reader);


    }

0

我即使捕获了异常,仍然遇到了错误。

    try {
        bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
    } catch (IOException e) {
        Log.e("blabla", "Error", e);
        finish();
    }

问题在于未导入IOException。
import java.io.IOException;

0

从键盘读取输入类似于从互联网下载文件,Java IO系统使用InputStream或Reader打开与要读取的数据源的连接,您必须使用IOExceptions处理连接可能中断的情况。

如果您想确切了解如何使用InputStream和BufferedReader工作,此视频可以展示它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接