如果我尝试在DB中插入现有对象,我会得到一个抛出异常的方法。
public void addInDB() throws Exception {
if (isInBase()){
throw new Exception ("[ReqFamily->addInDB] requirment already in base");
}
int idParent = m_parent.getIdBdd();
idBdd = pSQLRequirement.add(name, description, 0, idParent,
ReqPlugin.getProjectRef().getIdBdd(), 100);
}
因此,当抛出异常时,我想抓住它并在我的托管bean中显示错误消息。
PS:在我的托管bean中,我只是调用方法:
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
ex.printStackTrace();
}
}
答案 0 :(得分:1)
试试这个:
try {
req.addInDB();//here i want to catch it
} catch (Exception ex){
ex.printStackTrace();
}
答案 1 :(得分:1)
抓住或抛出Exception
的不良做法。如果您使用的任何代码抛出已检查的异常,则只捕获该特定异常,并尝试最小化try-catch
块的大小。
class MyException extends Exception {
...
public void addInDB() throws MyException {
if (isInBase()){
throw new MyException ("[ReqFamily->addInDB] requirment already in base");
}
...
void addReq(Requirement req){
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
try {
req.addInDB();
} catch (MyException ex){
ex.printStackTrace();
}
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
}
答案 2 :(得分:1)
你可以试试这个:
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
如果您想捕获要在显示中显示的所有堆栈跟踪,您可以使用:
catch (Exception ex) {
String
ls_exception = "";
for (StackTraceElement lo_stack : ex.getStackTrace()) {
ls_exception += "\t"+lo_stack.toString()+"\r\n";
}
JOptionPane.showMessageDialog(null, ls_exception);
}