Java 有例外,但没有被抓住
我不明白为什么。。。我有两个例外,但我不能抓住他们 在一个库中,我有一段代码,它抛出两种不同的异常Java 有例外,但没有被抓住,java,exception-handling,Java,Exception Handling,我不明白为什么。。。我有两个例外,但我不能抓住他们 在一个库中,我有一段代码,它抛出两种不同的异常 try { statement = con.prepareStatement(query); if (statement.executeUpdate() != 1) { throw new InvalidIndexException("Record not found or not modified", query); } } catch (SQLExcep
try {
statement = con.prepareStatement(query);
if (statement.executeUpdate() != 1) {
throw new InvalidIndexException("Record not found or not modified", query);
}
} catch (SQLException e) {
throw new DatabaseIOException(e, "", "SQL Error", logQuery);
}
已修改查询以触发SQL错误。发生时,我有一个日志条目:
2013-04-26 12:19:39 class database.DatabaseIOException
userManagement.Login.setActivationFlag(Login.java:473)
-> SQL Error
[QUERY]: UPDATE login SET activationprTTTTocess='false' WHERE id=235423432
[MSG]: ERROR: column "activationprttttocess" of relation "login" does not exis
因此,我确信sqlerror已被捕获并作为DatabaseIOException重新抛出,我也使用Netbeans跟踪了调试模式下的代码执行。现在一切正常
现在我有了一个servlet,尝试在其中激活用户:
try{
Login.setActivationFlag(235423432, false);
} catch (DatabaseIOException db) {
Log.addItem(db.getMessage());
} catch (InvalidIndexException ed){
Log.addItem(ed.getMessage());
}
不管我怎么想,都没有办法进入任何拦网。执行Login.setActivationFlag行时,日志上会出现错误(如上所示),但会跳过catch块,就像什么都没有出现一样
我不明白为什么会有这种奇怪的行为。我使用这些例外情况已经三年了,没有任何问题。。。
这段代码一定有一些我看不到的愚蠢之处。…您是否捕获了相同类型的DatabaseIOException?如果在同名的不同名称空间中出现异常,并且自动完成通过导入该类“有帮助”,您将获得所描述的行为。经过大约4个小时的调试,我发现了它是什么:处理异常时最糟糕的事情 在setActivationFlag()中,return语句放错了位置。。。它落在最终块中
...
} finally {
...
return done;
}
}
而不是
...
} finally {
...
}
return done;
}
编辑:
这里有一段代码要测试
public void ExceptionTest() throws Exception {
try {
Integer test = null;
test.toString();
} catch (NullPointerException e) {
out.println("Catched inner NullPointerException");
throw new Exception("My Exception", e);
} finally {
return;
}
}
public void test() {
try {
ExceptionTest();
} catch (Exception outer) {
out.println("Catched: " + outer.getMessage());
}
}
使用finally块中的return语句,外部异常永远不会被捕获。那么,有谁能提供帮助呢?主要取决于搜索键。这个错误非常臭名昭著,但很难发现。我修改了标题,希望它更具代表性。问题是您没有包含任何有助于诊断问题的代码。我认为,考虑到您在问题中的声明,您的解决方案没有任何意义——如果代码抛出异常,那么来自finally块的返回无论如何都不重要,异常仍然会被抛出,并且是可捕获的。现在使用该示例会更好吗?在这种情况下,异常是不可捕获的。