IOException异常;必须被抓住或宣布被抛出

时间:2013-06-19 14:47:14

标签: java io

您好我正在尝试运行一些java但是我不断收到错误消息,这是消息: unreported exception IOException; must be caught or declared to be thrown myName = in.readLine();

    import java.io.*;
public class While{
    public static void main(String []args){
        int num = 0;
        while (num != 999){
            System.out.println("Enter a number:");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            num = Integer.parseInt(in.readLine());
            System.out.println("You typed: " + num);
        }
        System.out.println("999 entered, so the loop has ended.");
    }
}

刚刚出去,我没有使用过java,这是我第一次使用它,我的老板问我是否可以看看它到目前为止我已经能够做到的一切我无法修复此错误消息,欢迎任何和所有帮助。

1 个答案:

答案 0 :(得分:6)

使用try-catch语句对代码进行环绕,并在BufferedReader循环之前移动while初始化。此外,请确保在使用后始终关闭资源。

public static void main(String []args) {
    int num = 0;
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(System.in));
        while (num != 999){
            System.out.println("Enter a number:");
            num = Integer.parseInt(in.readLine());
            System.out.println("You typed: " + num);
        }
    } catch (Exception e) {
        //handle your exception, probably with a message
        //showing a basic example
        System.out.println("Error while reading the data.");
        e.printStacktrace(System.in);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                System.out.println("Problem while closing the reader.");
                e.printStacktrace(System.in);
            }
        }
    }
    System.out.println("999 entered, so the loop has ended.");
}

如果您使用的是Java 7,则可以使用try with resources语句来利用所有代码:

public static void main(String []args) {
    int num = 0;
    try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
        while (num != 999){
            System.out.println("Enter a number:");
            num = Integer.parseInt(in.readLine());
            System.out.println("You typed: " + num);
        }
    } catch (Exception e) {
        //handle your exception, probably with a message
        //showing a basic example
        System.out.println("Error while reading the data.");
        e.printStacktrace(System.in);
    }
    System.out.println("999 entered, so the loop has ended.");
}