-1

如果我尝试在数据库中插入现有对象,我会得到一个抛出异常的方法。

 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();
    }
}
4

3 回答 3

1

试试这个:

        try {
            req.addInDB();//here i want to catch it 
        } catch (Exception ex){
            ex.printStackTrace();
        }
于 2012-11-16T16:16:32.427 回答
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);
    }
}
于 2012-11-16T16:19:13.713 回答
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);
}
于 2012-11-16T16:22:00.203 回答