2016-08-28 12 views
1

메서드 선언에서 예외를 throw하려고 할 때 "ClassNotFoundException에 연결할 수없는 catch 블록."예외 오류가 발생합니다.이 예외는 try 문 본문에서 throw되지 않습니다. "메서드에서 throw 예외를 catch 할 수 있습니까?

public class MenuSQL { 
    private static String sentence = ""; 
    private static int option; 
    Statement sentenceSQL = ConnectSQL.getConexion().createStatement(); 

public MenuSQL(int option) throws ClassNotFoundException, SQLException { 
    super(); 
    this.option = option; 
    try { 
     System.out.print("Introduce the sentence: "); 
     System.out.print(sentence); 
     sentence += new Scanner(System.in).nextLine(); 
     System.out.println(MenuSentence.rightNow("LOG") + "Sentence: " + sentence); 

     if (opcion == 4) { 
      MenuSentence.list(sentence); 
     } else { 
      sentenceSQL.executeQuery(sentence); 
     } 
    } catch (SQLException e) { 
     System.out.println(MenuSentence.rightNow("SQL") + "Sentence: " + sentence); 
    } catch (ClassNotFoundException e) { 
     System.out.println(MenuSentence.rightNow("ERROR") + "Sentence: " + sentence); 
    } 
} 
} 

가 어떻게 ClassNotFoundException을 잡을 수 :

코드는 다음인가? 미리 감사드립니다.

+1

왜 당신의'try' 블록에 던져 질 수없는 예외를 잡기를 원합니까? 왜 당신의 방법은 예외를 던집니까? –

+0

메소드 내에 ClassNotFoundException이 던져 질 수있는 지점이 없습니다. –

+0

그것은 컴파일러 강제로 나를 던져 방법에 예외가 –

답변

2

try{...} catch(){...}의 catch 블록은 try{...} 블록에 의해 throw 된 예외 만 catch 할 수 있습니다.

try { 
    Integer.parseInt("1"); 
    //Integer.parseInt throws NumberFormatException 
} catch (OtherException e) { 
    //Handle this error 
} 

것은 당신의 try{...} 블록을 던져 OtherException의 진술 중 어느 것도, 컴파일러가 제공되지 않습니다 때문에 (또는 그 예외의 슈퍼 클래스)

try { 
    Integer.parseInt("1"); 
    //Integer.parseInt throws NumberFormatException 
} catch (NumberFormatException e) { 
    //Handle this error 
} 

그러나, 당신은 무엇을하려고하는 것은 기본적으로 이것이다 당신은 오류가 있기 때문에 아무 것도 귀하의 try{...} 블록에 그 예외를 던질 것이라고 알고 있기 때문에, 결코 뭔가가하려고하지 말았어야 thrown 뭔가.

귀하의 경우 try{...} 블록에있는 어떤 것도 ClassNotFoundException을 던지지 않으므로 잡을 필요가 없습니다. 코드에서 catch (ClassNotFoundException e) {...}을 제거하여 오류를 수정할 수 있습니다.

+0

알렉스. 귀하의 정보는 매우 유용합니다. –