如何创建Exception与预制类型不同的新特性?
public class InvalidBankFeeAmountException extends Exception{
public InvalidBankFeeAmountException(String message){
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
它将显示在第一行中写入的InvalidBankFeeAmountException的警告.
我所做的所有谷歌搜索似乎都集中在"捕捉"错误上.如果满足某些条件,我希望能够提高自己.我尝试使用Error()类及其子类,但Eclipse无法识别它们.
这就是我想要做的:
if(some_condition) {
foobar();
}
else {
// raise an error
}
Run Code Online (Sandbox Code Playgroud)
愚蠢的问题,我知道,但我已经完成了我的谷歌搜索,我认为有人可以帮助我.
提前致谢!
感谢大家!如果你将来读这篇文章,这里是瘦的:
Java中的错误指的是您不应该尝试捕获的问题
例外是指您可能想要捕获的错误.
这是我的"修复"代码:
if(some_condition) {
foobar();
}
else {
throw new RuntimeError("Bad.");
}
Run Code Online (Sandbox Code Playgroud)
我RuntimeError()之所以使用是因为,正如一个答案所指出的那样,我不必事先声明我正在抛出一个错误,因为我依赖于一个条件,这非常有用.
谢谢大家!
我有一些功能与数据库一起工作.我在这里设置了一个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); …Run Code Online (Sandbox Code Playgroud)