【问题标题】:Unresolved compilation: Unhandled exception type IOException未解决的编译:未处理的异常类型 IOException
【发布时间】:2012-01-22 03:08:28
【问题描述】:

当尝试从标准中读取 int 时,我遇到了编译错误。

System.out.println("Hello Calculator : \n");        
int a=System.in.read();

程序抛出异常:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)

如何解决这个错误?

我的代码:

try {
    Scanner sc = new Scanner(System.in);
    int a=sc.nextInt();
} catch (Exception e) {
    // TODO: handle exception
}

【问题讨论】:

  • 先得到一个好的java教程。
  • 我试图让问题变得更好,并提供了一个不错的答案。

标签: java exception exception-handling


【解决方案1】:

in.read() 可以抛出一个 IOException 类型的检查异常。

您可以阅读 Java 中的异常处理Here.

您可以更改程序以引发 IOException,也可以将读取放入 try catch 块中。

try{
   int a=System.in.read();
catch(IOException ioe){
   ioe.printStackTrace();
}

public static void main(String[] args) throws IOException {
    System.out.println("Hello Calculator : \n");
    int a=System.in.read();
}

【讨论】:

    【解决方案2】:

    程序没有错误。

    read() 方法要求您捕获Exception,以防出现问题。

    将方法括在try/catchstatement 中:

    try {
     int a = System.in.read();
     ...
    }
    catch (Exception e) {
     e.printStackTrace();
    }
    

    无论如何我强烈建议您使用文档和/或 Java 教程,其中明确说明了这些内容。不使用它们进行编程是毫无意义的。您将为自己省去很多麻烦,而且可能还节省我们的时间。

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2011-01-19
      • 2017-12-02
      • 1970-01-01
      相关资源
      最近更新 更多