2012-12-19 4 views
0

가능한 중복 : 나는 다음과 같은 알고리즘을 사용하여 오일러 # 8를 해결하기 위해 노력하고있어
Why do I get the “Unhandled exception type IOException”?처리되지 않은 예외 유형 IOException이

. 문제는 내가 거대한 주석이있는 행을 수정할 때 //###이라고 표시된 행에 오류 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

메소드 시그니처에 throw를 추가했지만 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 위임 사항이 있습니다.

이 예외 유형은 이며 예외가 확인되었습니다. (그들은 unhandable있어 주로하기 때문에 - 예를 들어, OutOfMemoryException) 체크되지 예외가 존재하고 자바는 다음을 처리 할 필요가 없습니다 귀하의 취급을 잡기 그것을 무시 포함 할 수

참고. 이것은 좋은 생각이 아니다,하지만 자바는 정말 :-)

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) {} 
    } 
} 
관련 문제