Salesforce: APEX : Exception handling and custom user defined exceptions

Exception : Exception is an error which occurs at program run time, 

Always prepare your code for any unexpected error,
 




Examples: predefined salesforce exceptions : System.MathException , System.NullPointerException ( explore more )

E.g.

A)    You tried to refer a null object during run time
  
        Account act = null;
        System.debug(act.Name);    // System.NullPointerException


B)    Tried to divide Integer by Zero
        Integer i= 1/0; // System.MathException

//VisualforceException e

Mainly there are three keywords related to exception handling :
try, catch, finally

try{  
      // try block: where developer expect run time error
     // try block
     System.debug('we are in try block');
     String name = null;
     Integer i = name.length();
}
catch(Exception e){
    // catch block: this is block where developer catch the error and handles accordingly
    System.debug('we are in catch block');
}
finally{
    // finally block: this is block which gets executed after previous steps
    // executes always even if no exception thrown
    System.debug('we are in finally block');
}


//if you read debug log it will be as following
USER_DEBUG|[3]|DEBUG|we are in try block
EXCEPTION_THROWN|[5]|System.NullPointerException: Attempt to de-reference a null object
USER_DEBUG|[8]|DEBUG|we are in catch block
USER_DEBUG|[11]|DEBUG|we are in finally block


How to define your own custom exception with your own error message?

public class CustomExceptionTest{
      
// define custom exception


class ClassOverFlowException extends Exception{

  override public String getMessage(){
  return 'Class is over filled with Students, no more students';
  }
 



// extending custom exception class for Exception must end with "Exception" 
//else you get Compile Error: Invalid type

// declare custom exception variable
        ClassOverFlowException clsOverFlwException = null;

        public CustomExceptionTest(){
            // create object
            clsOverFlwException = new ClassOverFlowException();


        }


        Integer studentsLimit = 5; // define some custom limit for error condition
        List<String> studentNames = new String[]{'Rob','Bob','Tom','Kim'};   // define custom student names list

        public Boolean addStudent(String newStudentName){ // perform add operation
            Boolean isOpsSuccesful = false;
          
            try{  
              
                // check if list size   
                if(studentNames.size() >= studentsLimit) // if true // student list exceeding limit then
                throw clsOverFlwException; // throw error
                else
                studentNames.add(newStudentName);

                isOpsSuccesful = true;

            }
            catch(Exception e){
                isOpsSuccesful = false;
                System.debug('we are in catch block');
                System.debug(e.getMessage());
            }
            finally{
              
                if(isOpsSuccesful)
                System.debug('Ops successful');
                else
                System.debug('Ops failed, ');
               }
               return isOpsSuccesful ;

        }
}

//execute following

CustomExceptionTest a = new CustomExceptionTest();
//current list size id 4  ('Rob','Bob','Tom','Kim') and limit is 5 so we are good
a.addStudent('John'); // success

//current list size id 5  and limit is 5 so we are not good
 a.addStudent('Mac');  // failure with message "Class is over filled with Students, no more students"

Comments

  1. find sfdc tests and quiz @ http://www.exampeta.com/v/agpzfmV4YW1wZXRhchgLEgtVc2VyUHJvZmlsZRiAgICAgMijCww

    ReplyDelete

Post a Comment

Popular Posts