【问题标题】:Specifying throws IOException指定抛出 IOException
【发布时间】:2015-07-26 11:35:27
【问题描述】:

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

线程“主”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);
    }

}

【问题讨论】:

  • 这是您的实际代码吗?
  • 嗯,异常消息总结了您需要知道的所有内容must be caught or declared to be thrownand
  • 您需要声明您的代码在 Java 中无法处理的所有异常。因此,为了使您的代码能够编译,您要么需要在自己的 try-catch 中处理任何 IOException,要么必须指定该函数可以抛出 IOException。
  • 你有什么问题?看起来你解决了你的问题?

标签: java exception try-catch throws


【解决方案1】:

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

【讨论】:

  • 非常感谢大家澄清我对 IOException 的概念。
  • 这应该被修改为不再有throws IOException,因为它是通过catch处理的。
猜你喜欢
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 2014-06-28
相关资源
最近更新 更多