无法使用Java捕获自定义异常

时间:2017-09-10 11:22:59

标签: java exception-handling

我试图捕获SQL异常。我有三层,

  1. 控制器2. Impl类3. DAO(流程中也有一个接口,在高级别上我将3个级别作为描述)。
  2. 控制器

    try {
            // Call interface which in turn will call Impl
        } catch (MyException e) {
            logger.debug(e);
        } catch(Exception e) {          
            logger.debug(e);
        }
            return null;
    

    默认地将Impl

     try {
            purchaseDto = purDAO.createPurchase(clientId);
        } catch(MyException e) {  --> It should catch here, as I'm throwing MyException in DAO
            throw e;
        }catch(Exception e) { --> DAO Exception is being catch here
            throw e;
        }
    

    DAO

     try {
              // My business logic goes here     
        } catch (SQLException e) {            
            throw new MyException (e.getErrorCode(), e.getMessage()); --> It is catching here, from here it should go back to Impl catch block of MyException
         } catch (Exception e) {            
            e.printStackTrace();
        } finally {
            pt.close();
            try{                
                if (con != null)
                    con.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    

    我的例外

    public class MyException extends Exception {
    
    /**
     * 
     */
    private int errorCode;
    private String errorDesc;
    
    
    public int getErrorCode() {
        return errorCode;
    }
    
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
    
    public String getErrorDesc() {
        return errorDesc;
    }
    
    public void setErrorDesc(String errorDesc) {
        this.errorDesc = errorDesc;
    }
    
    private static final long serialVersionUID = 1L;
    
    public MyException () {
        super();
    }
    
    public MyException (int errorCode, String errorDesc) {
        super();
        this.errorCode = errorCode;
        this.errorDesc = errorDesc;
    }
    
    
    
    }
    

    我在DAO层中遇到sql异常,如果我得到任何sql异常,我会抛出自定义异常。当它返回到Impl时,它会转到正常的异常catch块(它获取为空指针异常消息)。理想情况下它应该转到我的自定义异常捕获,对吧?我在哪里做错了。请纠正我。

    非常感谢任何想法。

1 个答案:

答案 0 :(得分:0)

最有可能的情况是DAO类中的行pt.close();会引发异常。在这种情况下,因为finally块中发生异常,所以不会抛出异常。 此处更详细地解释了此方案: https://stackoverflow.com/a/4264937/6169266

相关问题