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

2019-05-09 03:14发布

我有以下简单的代码:

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 

没有任何人有任何想法,为什么? 我只是试图以简化的总和网站(给出的代码在这里 )。 我是不是过于简单化?

Answer 1:

您应该添加“抛出IOException异常”你的主要方法:

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

你可以阅读更多的关于checked异常(这是特定于Java)在JLS 。



Answer 2:

Java有一个名为“checked异常”功能。 这意味着,有一定类型的异常,即那些子类异常,但不是RuntimeException的,例如,如果一个方法可能引发它们,就必须在其抛出的声明一一列举了,说:孔隙READDATA()抛出IOException异常。 IOException异常是其中之一。

因此,当你拨打列出IOException异常在其抛出声明中的方法,您必须列出它在自己的抛出声明或捕获它。

对于检查型异常的存在的理由是,对于某些类型的异常,你不能忽视的事实是,他们可能会发生,因为他们的情况是相当正常状况下,不是一个程序错误。 因此,编译器可以帮助你不约而提出了这样的异常的可能性忘记,需要你来处理它以某种方式。

然而,并非所有检查的异常类在Java标准库合此理之下,但是这是一个完全不同的主题。



Answer 3:

与此代码段再试一次:

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



Answer 4:

从键盘读取输入类似于从互联网上下载文件,Java的IO系统将打开数据源连接到使用InputStream或Reader阅读,你必须处理的情况下的连接可以使用的IOExceptions突破

如果你想知道到底是什么意思与InputStreams工作和BufferedReader 该视频显示它



Answer 5:

添加“抛出IOException异常”到你的方法是这样的:

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

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

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


    }


文章来源: Why do I get the “Unhandled exception type IOException”?