2012-03-15 2 views
5
public class ThrowException { 
    public static void main(String[] args) { 
     try { 
      foo(); 
     } 
     catch(Exception e) { 
      if (e instanceof IOException) { 
       System.out.println("Completed!"); 
      } 
      } 
    } 
    static void foo() { 
     // what should I write here to get an exception? 
    } 
} 

안녕하세요! 나는 방금 예외를 배우기 시작했고 계획을 잡을 필요가있다. 그래서 아무도 나에게 해결책을 제공 할 수 있니? 나는 매우 감사 할 것입니다. 감사합니다.IOException을 던지는 방법?

+0

'foo' 무엇을하고 어떻게 A''관련이 있습니까? –

+1

이것은 어떤 책이나 자바 소개가 가르쳐 줄 자바 구문 일뿐입니다. 나는 약간을 읽는 것이 좋습니다. – ColinD

답변

15
static void foo() throws IOException { 
    throw new IOException("your message"); 
} 
+0

나는 이것을 foo 메서드에서 작성해야합니까? –

+0

예. 이 행에 도달하면 예외가 발생합니다. –

+1

예외를 throw하려면 foo 메서드를 선언해야합니다. 그렇지 않으면 컴파일러 오류가 발생합니다. – ewok

6
try { 
     throw new IOException(); 
    } catch(IOException e) { 
     System.out.println("Completed!"); 
    } 
1
throw new IOException("Test"); 
1

난 그냥 예외를 배우기 시작하고

이 예외가 더하지 잡으려고 예외

throw new IOException("Something happened") 

를 throw되는 예외를 잡을 필요 Exception bec 사용 목표는 foo() 방법에서 예외를 던질 경우

try { 
    //code that can generate exception... 
}catch(IOException io) { 
    // I know how to handle this... 
} 
1

, 다음과 같이 선언해야합니다 : ause 훨씬 일반적인 대신, 당신이 처리하는 방법을 알고 특정 예외를 잡을이다

그런 다음 주에
public void foo() throws IOException{ 
    \\do stuff 
    throw new IOException("message"); 
} 

:

public static void main(String[] args){ 
    try{ 
     foo(); 
    } catch (IOException e){ 
     System.out.println("Completed!"); 
    } 
} 

하는 것으로, foo는 하나가 컴파일러 오류가 발생합니다 잡으려고 시도, IOException를 던져 선언하지 않는 한. catch (Exception e)instanceof을 사용하여 코딩하면 컴파일러 오류가 방지되지만 불필요합니다.

0

아마이

참고 청소기 방법은 아래의 예에서 예외를 포착하는 데 도움이 ... - 당신이 e instanceof IOException 필요하지 않습니다.

public static void foo() throws IOException { 
    // some code here, when something goes wrong, you might do: 
    throw new IOException("error message"); 
} 

public static void main(String[] args) { 
    try { 
     foo(); 
    } catch (IOException e) { 
     System.out.println(e.getMessage()); 
    } 
} 
1

다음 코드 시도하십시오 :

throw new IOException("Message"); 
관련 문제