假设您首先需要像这样嵌套 try-catch 块,这没有任何问题。对于您提供的示例, Maroun 的回答会更好。如果您在“光标”清理中涉及大量局部变量,则您建议的方法更适合的示例可能是:
openDatabaseConnection();
try {
Cursor cursor = openCursor();
CursorHelper helper = new CursorHelper(cursor);
String cursor_id = cursor.getId();
String something_else = cursor.getSomethingElse();
try {
useCursor(cursor_id, something_else, helper);
} finally {
closeCursor(cursor_id, something_else, helper);
}
} catch (Exception e) {
genericLogError();
} finally {
closeDatabaseConnection();
}
父 try 块将捕获嵌套块抛出的异常,但嵌套finally
块将首先被调用。这将游标变量的范围保持在第一个try/catch
块中。
如果您想将所有这些代码拉到一个try/catch
块中,则必须在该块之外声明一些变量,这可能会开始影响可读性:
openDatabaseConnection();
CursorHelper helper = null;
String cursor_id = null;
String something_else = null;
try {
Cursor cursor = openCursor();
helper = new CursorHelper(cursor);
cursor_id = cursor.getId();
something_else = cursor.getSomethingElse();
useCursor(cursor_id, something_else, helper);
} catch (Exception e) {
genericLogError();
} finally {
if (cursor_id != null) {
closeCursor(cursor_id, something_else, helper);
}
closeDatabaseConnection();
}