首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指定抛出IOException

指定抛出IOException
EN

Stack Overflow用户
提问于 2015-05-14 18:08:59
回答 1查看 1.3K关注 0票数 1

有人能帮我解决我的问题吗。我是Java编程的初学者。以前,当我没有声明抛出IOException时,它给了我一个错误:

线程"main“java.lang.RuntimeException中的异常:不可编译的源代码-未报告的异常java.io.IOException;必须捕获或声明抛出

该方案如下:

代码语言:javascript
复制
import java.io.*;

public class addition {
    public static void main(String array[])throws IOException
    {
        InputStreamReader i = new InputStreamReader(System.in);
        BufferedReader b = new BufferedReader(i);
        System.out.println("Enter first number : ");
        int a1 = Integer.parseInt(b.readLine());
          System.out.println("Enter second number : ");
        int a2 = Integer.parseInt(b.readLine());
        int sum = a1 + a2 ;
        System.out.println("addition"+sum);
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-14 18:19:37

如果在尝试从输入流读取时出现I/O故障,BufferedReader函数readLine()将抛出一个IOException。在Java中,如果出现异常,必须使用try catch语句来处理它们:

代码语言:javascript
复制
import java.io.*;

public class addition {
public static void main(String array[])throws IOException
{
    InputStreamReader i = new InputStreamReader(System.in);
    BufferedReader b = new BufferedReader(i);
    System.out.println("Enter first number : ");

    // Attempt to read in user input.
    try {
        int a1 = Integer.parseInt(b.readLine());
        System.out.println("Enter second number : ");
        int a2 = Integer.parseInt(b.readLine());
        int sum = a1 + a2 ;
        System.out.println("addition"+sum);
    }

    // Should there be some problem reading in input, we handle it gracefully.
    catch (IOException e) {
        System.out.println("Error reading input from user. Exiting now...");
        System.exit(0);
    }
}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30244337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档