2013年7月20日 星期六

throw and throws


  • throw new exception(接收該method的exception)
  • throws exception(該method不處理execption, retrun to caller)
而你不使用try..catch處理,則表示目前環境資訊不足以處理exception,必須由屆時使用該方法的客戶端依當時環境資訊進行處理,為了告訴編譯器這件事實,則必須在method上使用throws宣告會丟出exception,那麼compiler才會讓你通過
  • StackTrace

  1. try{ 
  2.  int x = 5/0; 
  3.  } catch(Exception e){ 
  4.  e.printStackTrace(); 
  5.  }



Example:


public HxAccg getHxAccgByAccNo(String acc_no) throws Exception
    {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        HxAccg record = null;
        try
        {
            conn = getDataSource().getConnection();
            pstmt = conn.prepareStatement("SELECT * FROM HD_ACCG_ACT WHERE ACC_NO = ? ");
            pstmt.setString(1, acc_no);
            rs = pstmt.executeQuery();
            if (rs.next())
            {
                record = fillHxAccgByResultSet(rs);
            }
        }
        catch (Exception ex)
        {
        loggor.error("依照存取單號取得報到資料發生錯誤,存取單號="+acc_no, ex);
        throw new Exception("依照存取單號取得報到資料發生錯誤,存取單號="+acc_no,ex);
        }
        finally
        {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        }

        return record;

    }

沒有留言:

張貼留言