我有一些功能与数据库一起工作.我在这里设置了一个try/catch错误处理,并显示一条消息,它工作正常.
现在,调用此删除函数的类需要知道是否存在错误.在我的情况下:如果成功则刷新GUI,如果失败则无需执行操作(因为已经显示消息消息对话框).
我想出了一个在这个函数中返回布尔值的想法.
public static Boolean delete(int id){
String id2 = Integer.toString(id);
try {
String sql =
"DELETE FROM toDoItem " +
"WHERE id = ?;";
String[] values = {id2};
SQLiteConnection.start();
SQLiteConnection.updateWithPara(sql, values);
} catch (SQLException e) {
Main.getGui().alert("Fail when doing delete in DataBase.");
System.out.println("Exception : "+ e.getMessage());
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
不知道这是好还是坏,请告诉我.
编辑:
以下是我如何使用的更多细节:
假设上面的代码在Class A中,在B类中:
public boolean deleteItem(int id){
int i = index.get(id);
if(theList[i].delete()){ //<---- here is the function from Class A
theList[i] = null;
index.remove(id);
retutn true;
}
retutn false;
}
Run Code Online (Sandbox Code Playgroud)
我需要在多个类中传递布尔值,我不知道是否可以更好地通过...
在C类:
public void toDoList_deleteItem(){
MyButton btn = (MyButton)source;
int id = btn.getRefId();
List toDoList = Main.getToDoList();
if(toDoList.deleteItem(id)){ //<-------function in Class B
Main.getGui().refresh();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑2:
我注意到这个问题在某种程度上更有可能问"我应该在数据库层处理一个影响到GUI层的异常?"......就像这样.如果要编辑问题标题,请更正我.
看起来您正在返回boolean状态以指示已发生异常情况.一般来说,这不是一个好习惯,原因有两个:
更好的方法是定义特定于应用程序的异常,并在API中使用它.这会强制API的用户注意可能发生的异常情况,同时允许您根据需要传递尽可能多的(或尽可能少的)其他信息.同时,您的代码不会受到if (!delete(id)) { /* handle error */ }每个API调用上的代码污染,缩小代码库并提高其可读性.
你能告诉我更多关于"定义特定于应用程序的异常"的信息,或者请展示一些代码示例吗?
我将如何做到这一点:
public class DataAccessException extends Exception {
... // Define getters/setters for passing more info about the problem
}
...
public static void delete(int id) throws DataAccessException {
try {
... // Do something that may lead to SQLException
} catch (SQLException se) {
// Do additional logging etc., then
throw new DataAccessException("Error deleting "+id, se);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:通常会给自定义异常提供四个构造函数,这些构造函数镜像Exception类的构造函数以允许异常链接.这里描述了构造函数.
不要返回 a Boolean,返回 a boolean。由于这不是异常/错误情况,所以没关系。