2012-11-16 45 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); 
} 
相關問題