任何人都可以帮我解决我的问题。我是Java编程的初学者。以前当我没有声明抛出IOException 时,它给了我一个错误:
线程中的异常" main" java.lang.RuntimeException:无法编译 源代码 - 未报告的异常java.io.IOException;必须抓住 或宣布被抛出
该计划如下所示:
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);
}
}
答案 0 :(得分:0)
如果在尝试从输入流中读取时发生I / O故障,则BufferedReader函数readLine()会抛出IOException。在Java中,必须使用try catch语句来处理出现的异常:
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);
}
}
}