Sunday 21 September 2014

Custom Exception in Salesforce

public class CustomExceptionClass {
   
// define custom exception with extend the built-in Exception class
// And make sure your class name ends with the word Exception,
// else you get Compile Error: Invalid type

class MyException extends Exception{

    //Override the getMessage method of Exception class to show you custom Error
  override public String getMessage(){
  return 'The Show is HouseFull, No more Tickets are available';
  }

}

// declare custom exception variable
        MyException myExceptionVar = null;
   
 //Constractor of OuterClass
        public CustomExceptionClass(){
            // create object of Custom Exception class
            myExceptionVar = new MyException();

        }

        Integer TotalTickets = 5; // define some custom limit for error condition
 // Define some person name who booked ticket
        List<String> PersonName = new String[]{'Harry','Ron','Hermione'};  

        public Boolean addPerson(String newPersonName){ // Add another person
            Boolean TicketBooked = false;
         
            //use try Catch for Exception
            try{  
                    //Check the List
            if(PersonName.size() >= TotalTickets) // If return True then throw Exception
           throw myExceptionVar;
                    // Throw Exception it'll show the error which we written in getMessage
               
                else //Else Add the Person name
                PersonName.add(newPersonName);

                TicketBooked = true;

            }
            //Catch block
            catch(Exception e){
                TicketBooked = false;
                System.debug('we are in catch block');
                System.debug(e.getMessage());
            }
            finally{
             
                if(TicketBooked)
                System.debug('Ticket Booked successfully');
                else
                System.debug('Booking failed');
               }
               return TicketBooked ;

        }
}


// Execute Following

CustomExceptionClass a = new CustomExceptionClass();
//Current list size is 3  ('Harry','Ron','Hermione') and limit is 5 so we can add two more

a.addPerson('Viru'); // Ticket Booked Successfully
a.addPerson('Emma'); // Ticket booked Successfully

//current list size id 5  and limit is 5 so we are not good
a.addPerson('Draco');  //Booking failed 

No comments:

Post a Comment