title: Better way for DB exception handling in java
body: <p>Which one will be better: ErrorCode or Exception for that situation?</p>
  
  <p>I have ever been seeing these two error handling techniques. I don't know the disadvantages and advantages for each technique.</p>
  
  <pre><code>public void doOperation(Data data) throws MyException {
      try {
          // do DB operation
      } catch (SQLException e) {
          /* It can be ChildRecordFoundException, ParentRecordNotFoundException
           * NullValueFoundException, DuplicateException, etc..
           */
          throw translateException(e);
      }
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>public void doOperation(Data data) throws MyException {
      try {
          // do DB operation
      } catch (SQLException e) {
          /* It can be "CHILD_RECORD_FOUND, "PARENT_RECORD_NOT_FOUND"
           * "NULL_VALUE_FOUND", "DUPLICATE_VALUE_FOUND", etc..
           */
          String errorCode = getErrorCode(e);
          MyException exc = new MyException();
          exc.setErrorCode(errorCode);
          throw exc;
      }
  }
  </code></pre>
  
  <p>For second method, the error code retrieve form configuration file. We can add <code>Error Code</code> based on the <code>SQL Vender Code</code>.</p>
  
  <p>SQL_ERROR_CODE.properties</p>
  
  <pre><code>#MySQL Database
  1062=DUPLICATE_KEY_FOUND
  1216=CHILD_RECORD_FOUND
  1217=PARENT_RECORD_NOT_FOUND
  1048=NULL_VALUE_FOUND
  1205=RECORD_HAS_BEEN_LOCKED
  </code></pre>
  
  <p>Caller client for method 1</p>
  
  <pre><code>    try {
  
      } catch(MyException e) {
          if(e instanceof ChildRecordFoundException) {
              showMessage(...);
          } else if(e instanceof ParentRecordNotFoundException) {
              showMessage(...);
          } else if(e instanceof NullValueFoundException) {
              showMessage(...);
          } else if(e instanceof DuplicateException) {
              showMessage(...);
          }
      }
  </code></pre>
  
  <p>Caller client for method 2</p>
  
  <pre><code>    try {
  
      } catch(MyException e) {
          if(e.getErrorCode().equals("CHILD_RECORD_FOUND")) {
              showMessage(...);
          } else if(e.getErrorCode().equals("PARENT_RECORD_NOT_FOUND") {
              showMessage(...);
          } else if(e.getErrorCode().equals("NULL_VALUE_FOUND") {
              showMessage(...);
          } else if(e.getErrorCode().equals("DUPLICATE_VALUE_FOUND") {
              showMessage(...);
          }
      }
  </code></pre>