csc*_*aba 1 java exception-handling
如果我的代码中有异常处理部分,并且它可以触发4个sqlException,那么处理它们的最佳方法是什么,它最能说明发生了什么以及在哪里?我制作了一个穷人解决方案(使用'exceptionDesc').
处理这种情况有什么好的做法吗?(没有制作独特的类和子类)
try {
exceptionDesc = "prepareStatement";
statement = connection.prepareStatement(sql);
exceptionDesc = "statement.set...";
statement.setDate(1, sqlDate);
exceptionDesc = "executeUpdate";
statement.executeUpdate();
exceptionDesc = "commit";
connection.commit();
}
catch (SQLException sqlEx) {
if (exceptionDesc.equals("prepareStatement")) {
LOG.error ...
} else if (exceptionDesc.equals("executeQuery")) {
LOG.error(" executeQuery ...
...
...
throw new SQLException(sqlEx);
}
Run Code Online (Sandbox Code Playgroud)
什么都不做 异常的堆栈跟踪为您执行此操作:
catch (SQLException e) {
LOG.error("A SQLException happened", e);
throw e;
}
Run Code Online (Sandbox Code Playgroud)
足够了.记录器,如果配置为显示堆栈跟踪(它应该这样做),将打印堆栈跟踪,堆栈跟踪将确切地告诉哪个方法,在哪一行,抛出异常.它还将告诉哪个方法调用导致异常的方法等,直到堆栈的底部.