简体   繁体   中英

Can I catch a throw exception from method?

When I try to throw an exception from method declaration I get the error "Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body".

The code is this:

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);
    }
}
}

How can I catch ClassNotFoundException ? Thanks in advance.

The catch block of a try{...} catch(){...} statement can only catch exceptions thrown by the try{...} block. (Or a superclass of that exception)

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

However, what you are trying to do is basically this:

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

Because none of the statements in your try{...} block throw OtherException , the compiler will give you an error, because it knows that nothing in your try{...} block will ever throw that exception, so you should not try to catch something that is never thrown .

In your case, nothing in your try{...} block throws a ClassNotFoundException , so you don't need to catch it. You can remove the catch (ClassNotFoundException e) {...} from your code to fix the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM