我可以从方法中捕获抛出异常吗?

时间:2016-08-28 18:27:35

标签: java exception methods try-catch throws

当我尝试从方法声明中抛出异常时,我得到错误“ClassNotFoundException的无法访问的catch块。这个异常永远不会从try语句体中抛出”。

代码是这样的:

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 个答案:

答案 0 :(得分:2)

try{...} catch(){...}语句的catch块只能捕获try{...}块抛出的异常。 (或该异常的超类)

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

但是,你要做的基本上是这样的:

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

因为try{...}块中没有一个语句抛出OtherException,编译器会给你一个错误,因为它知道你try{...}中的没有阻止永远抛出该异常,因此您不应尝试catch永远不会thrown的内容。

在您的情况下,try{...}区块中的任何内容都不会引发ClassNotFoundException,因此您无需抓住它。您可以从代码中删除catch (ClassNotFoundException e) {...}以修复错误。