[英]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". 当我尝试从方法声明中引发异常时,出现错误“ ClassNotFoundException的Unreachable catch块。永远不会从try语句主体中引发此异常”。
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
? 如何捕获
ClassNotFoundException
? Thanks in advance. 提前致谢。
The catch block of a try{...} catch(){...}
statement can only catch exceptions thrown by the try{...}
block. try{...} catch(){...}
语句的catch块只能捕获try{...}
块引发的异常。 (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
. 因为没有在你的发言
try{...}
块扔OtherException
,编译器就会给你一个错误,因为它知道, 没有在你try{...}
块都不会抛出异常,所以你不应该尝试catch
永不thrown
东西。
In your case, nothing in your try{...}
block throws a ClassNotFoundException
, so you don't need to catch it. 就您而言,
try{...}
块中没有任何东西抛出ClassNotFoundException
,因此您无需捕获它。 You can remove the catch (ClassNotFoundException e) {...}
from your code to fix the error. 您可以从代码中删除
catch (ClassNotFoundException e) {...}
,以修复错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.