2012-12-19 78 views
0

可能重复:
Why do I get the “Unhandled exception type IOException”?未处理的异常类型为IOException

我尝试使用下面的算法来解决欧拉#8。问题是,当我修改该行时,我有一个巨大的评论,错误Unhandled Exception Type IOException出现在我用//###评论标记的每一行上。

private static void euler8() 
{ 
    int c =0; 
    int b; 
    ArrayList<Integer> bar = new ArrayList<Integer>(0); 
    File infile = new File("euler8.txt"); 
    BufferedReader reader = new BufferedReader(
          new InputStreamReader(
          new FileInputStream(infile), //### 
          Charset.forName("UTF-8"))); 
     while((c = reader.read()) != -1) { //### 
      char character = (char) c; 
      b = (int)character; 
      bar.add(b); /*When I add this line*/ 
     } 
    reader.close(); //### 
} 
+3

阅读[例外教程](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html),然后利用这些知识要么将代码包装在try/catch中,要么抛出异常 - 您的选择。 –

回答

5

是,IOException检查的异常,这意味着你要么需要抓住它,或宣布你的方法将它扔了。 如果抛出异常,想要发生什么?

请注意,无论如何,您通常应该在finally区块内关闭reader,以便在面临另一个异常时关闭。

查看Java Tutorial lesson on exceptions了解有关已检查和未检查异常的更多详细信息。

+0

我向方法签名添加了抛出,但如果我不包含try {},我将如何包含finally块? – Bennett

+0

@JamesRoberts - 你可以使用'try/finally'结构(没有任何'catch'块)。另一种方法是,如果您使用的是Java 7,则使用[try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)语句。 –

+0

此外,我不再在该方法中获取错误,但在方法调用中出现“未处理的异常类型IOException”错误。 – Bennett

0

包装在try/catch块中以捕获异常。

如果你不这样做,它会去处理。

0

如果您无法读取指定文件会发生什么情况? FileInputStream将抛出一个异常,Java要求您必须检查并处理它。

这种类型的异常被称为检查异常。 未选中例外情况存在和Java并不需要你来处理这些(主要是因为他们unhandable - 例如OutOfMemoryException

请注意,您的操作可能包括捕获它和忽略它。这不是一个好主意,但Java不能真正确定:-)

2

一个解决方案:改变

private static void euler8() throws IOException { 

但随后调用方法已经赶上IOException异常。

或捕获异常:

private static void euler8() 
{ 
    int c =0; 
    int b; 
    ArrayList<Integer> bar = new ArrayList<Integer>(0); 
    BufferedReader reader; 
    try { 
     File inFile = new File("euler8.txt"); 
     reader = new BufferedReader(
          new InputStreamReader(
          new FileInputStream(infile), //### 
          Charset.forName("UTF-8"))); 
     while((c = reader.read()) != -1) { //### 
      char character = (char) c; 
      b = (int)character; 
      bar.add(b); /*When I add this line*/ 
     } 
    } catch (IOException ex) { 
     // LOG or output exception 
     System.out.println(ex); 
    } finally { 
     try { 
      reader.close(); //### 
     } catch (IOException ignored) {} 
    } 
} 
相关问题