2012-11-16 42 views
-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(); 
    } 
} 
+1

你的意思是抓有例外和日志它并继续进一步处理? – kosa

+0

我的意思是防止抛出异常,而是向用户显示错误信息:该对象已经存在于数据库中 – AmiraGL

回答

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); 
    } 
} 
1

试试这个:

 try { 
      req.addInDB();//here i want to catch it 
     } catch (Exception ex){ 
      ex.printStackTrace(); 
     } 
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); 
} 
相关问题