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

时间:2010-02-21 13:14:07

标签: java stdin readline ioexception

我有以下简单的代码:

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 

有人有什么想法吗?我只是想简化总和网站(here)上给出的代码。我过度简化了吗?

6 个答案:

答案 0 :(得分:49)

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

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

您可以在JLS中阅读有关已检查异常(特定于Java)的更多内容。

答案 1 :(得分:42)

Java有一个名为“已检查异常”的功能。这意味着存在某些类型的异常,即那些子类Exception而不是RuntimeException,如果方法可能抛出它们,它必须在它们的throws声明中列出它们,例如:void readData()抛出IOException。 IOException就是其中之一。

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

存在已检查异常的基本原理是,对于某些类型的异常,您不能忽略它们可能发生的事实,因为它们的发生是非常常见的情况,而不是程序错误。因此,编译器可以帮助您不要忘记引发此类异常的可能性,并要求您以某种方式处理它。

但是,并非Java标准库中所有已检查的异常类都符合此基本原理,但这是一个完全不同的主题。

答案 2 :(得分:11)

请尝试使用此代码段:

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时,查找错误和调试会更容易。

答案 3 :(得分:0)

从键盘读取输入类似于从Internet下载文件,java io系统打开与使用InputStream或Reader读取的数据源的连接,您必须通过使用IOExceptions来处理连接可能中断的情况< / p>

如果您想确切知道使用InputStreams的意义,BufferedReader this video显示它

答案 4 :(得分:0)

将“抛出IOException”添加到您的方法中:

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

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

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


    }

答案 5 :(得分:0)

即使我捕获了异常,我也收到了错误。

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

问题是未导入 IOException

import java.io.IOException;