指定抛出 IOException
Specifying throws IOException
谁能帮我解决我的问题。我是 Java 编程的初学者。以前当我没有声明 throws 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 编程的初学者。以前当我没有声明 throws 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);
}
}
}