Amit Deshpande
Amit Deshpande

Reputation: 19185

Generic Exception Handling

I found below code for exception handling which handles all execptions of thrown by application including runtimes.

      public static void handleException(String strMethodName,
                    Exception ex) throws CustomException{
            String strMessage = "";
            try {
                throw ex;
            } 
            catch (NullPointerException npe){
                logger.log(pr, strMethodName, npe.getMessage());
                strMessage=ERR_02;
                throw new CustomException(strMessage);
            } 
            catch(IndexOutOfBoundsException iobe) {
                logger.logMethodException(strMethodName,iobe.getMessage());
                strMessage=ERR_03;
                throw new CustomException(strMessage);
            }
            ... So On
     }

Below are some of the disadvantages that I think:

  1. To idenitify root cause of the exception we will need to always check for the Message string.
  2. No sepearation of type of exceptions

Advantage:

  1. Less code. (Code can be minimized)

Can you please let me know whether I should go with such mechanism or not.

Upvotes: 0

Views: 559

Answers (1)

Ezhil V
Ezhil V

Reputation: 882

Not sure of the circumstances which you are using the code.

In your approach, you are not rethrowing the exception object which may be used for debugging

public static void handleException(String strMethodName,
                    Throwable th){
            String strMessage = "";
            try {
                throw th;
            } 
            catch (Throwable thr){
                logger.log(pr, strMethodName, npe.getMessage());
                //get the appropriate error code from a method
                strMessage=getErrorCode();
                throw new CustomException(strMessage, th); 
               //CustomException is of type RuntimeException
            }
     }

By catching and "THROWING" the Throwable object you are sure that even errors are handled properly. [It is important not to suppress the Throwable object]

Upvotes: 1

Related Questions