gpt4 book ai didi

java - 指定抛出 IOException

转载 作者:太空宇宙 更新时间:2023-11-04 13:51:20 24 4
gpt4 key购买 nike

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

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.IOException; must be caught or declared to be thrown

程序如下所示:

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);
}

}

最佳答案

如果在尝试从输入流读取时发生 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);
}
}
}

关于java - 指定抛出 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30244337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com