+ Start a Discussion
Kiran Kumar 225Kiran Kumar 225 

aused an unexpected exception, contact your administrator

Hi, I have the following code it is throwing 

trigger ContactCount on Contact (after insert, after delete, after undelete,after update) {
    set<string> AccountIds = new set<string>();
    if(trigger.isinsert || trigger.Isundelete){
        for(Contact Con: trigger.new){
            AccountIds.add(con.AccountId);
            system.debug('AccountID-->'+con.AccountId);
        }
    }
    if(trigger.isDelete || trigger.isupdate){
        system.debug('Delete');
        for(Contact oldCon : trigger.old){
            AccountIds.add(oldCon.AccountId);  
            system.debug('Delete---2');
        }
    }
    List<Account> accountList = [select id,count__c,(select id from contacts) from Account Where ID IN:AccountIds];
    list<account> accountupdate = new List<Account>();
    for(Account acc : accountList){
        system.debug('Contacts--->'+acc.contacts.size());
        acc.count__c = acc.contacts.size();
        //accountupdate.add(acc);
    }
    update accountList;

}

It is throwing unexpected exception error. Please let me konw where i did the mistake 
Best Answer chosen by Kiran Kumar 225
Mahesh DMahesh D
Hi Kiran,

Please find the below trigger:
 
trigger ContactCount on Contact (after insert, after delete, after undelete,after update) {
    set<Id> accIds = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Contact con: Trigger.new){
            accIds.add(con.AccountId);            
        }
    }
    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Contact con: Trigger.old){
            accIds.add(con.AccountId);            
        }
    }    
    
    List<Account> accList = [select id, count__c, (Select Id from contacts) from Account Where ID IN: accIds];
    
    for(Account acc : accList){
        system.debug('Contacts--->'+acc.contacts.size());
        acc.count__c = acc.Contacts.size();
    }
    update accList;
}

I already tested it in my DE and everything is working fine.

Please do let me know if it helps.

Regards,
Mahesh