function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
tulasi ram 1tulasi ram 1 

How to include catch block in code coverage

I am using below code
global static String updateContact(Contact objContact) {
        try{
            if(isContactUpdateable() || Test.isRunningTest()) {
                update objContact;
                return 'Contact updated successfully!';
            }
            else { return 'Insufficient access to update contact, please contact system admin for more information'; }
        }catch(Exception ex) { return '' + ex.getMessage(); }
    }

Unable to include catch block in code coverage. How can we include this catch blocks in code coverage.
Khan AnasKhan Anas (Salesforce Developers) 
Hi Tulasi,

I trust you are doing very well.

Please refer to the below link with a similar discussion which might help you further with the above issue.​

https://developer.salesforce.com/forums/ForumsMain?id=906F000000092nNIAQ

See answer from bob_buzzard in this link.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas
tulasi ram 1tulasi ram 1
Hi Khan Anas, i tried like below
public with sharing class HouseholdMemberController {
 
	public HouseholdMemberController() {
		
		System.debug('>>> HouseholdMemberController BEFORE shref');
		try {
	    	String shref = ApexPages.currentPage().getURL();
	    	System.debug('>>> HouseholdMemberController shref='+shref);
			if(Test.isRunningTest())
			{
				throw new Exception();
			}
			
		} catch (Exception e) {
			System.debug('>>> ERROR ='+e);
		}    		
	}    
}

but it is giving unreachable statement error. And it is saying that  'throw new Exception();' is not defined.
Khan AnasKhan Anas (Salesforce Developers) 
Tulasi,

You need to add below line of code in your class, above your method.
 
public class myException extends Exception {}

Regards,
Khan Anas
Raj VakatiRaj Vakati
try this .. you can make your test class fail and handle in the try and catch and which will cover the code
 
@istest
public class CatchCodeCoverage{

 @isTest static void testCallout() {
        Test.startTest() ;
		
		try{
			YOURCLASS.updateContact(NULL);
		}catch(Exception e){
			
		}
		
        Test.stopTest();
    }
}