0

I have below code where I face null pointer exception when the custom settings data is not populated. I simply need to ignore if it's null rather than getting an exception in this trigger code.

Can someone suggest a way out?

Apex Code:

 Abbvie_Custom_Settings__c settings = Abbvie_Custom_Settings__c.getInstance('Main');
  String  AllowedProfiles= settings.Allowed_Profiles_abv__c;

string[] part;
String profile='';
part = AllowedProfiles.split(',');    // This line throws null pointer exception
5

Simply do the Null check before performing split operation

Abbvie_Custom_Settings__c settings = Abbvie_Custom_Settings__c.getInstance('Main');

if(settings != null)
{
    String  AllowedProfiles= settings.Allowed_Profiles_abv__c;

    String[] part;
    String profile='';
    if(AllowedProfiles !=null)
    {
        part = AllowedProfiles.split(',');
    }
}
  • settings might also be null... – sfdcfox May 30 '17 at 16:18
4

Easy way to do this would be to use ternary operators:

Abbvie_Custom_Settings__c settings = Abbvie_Custom_Settings__c.getInstance('Main');

String[] part = settings == null || string.isBlank(settings.Allowed_Profiles_abv__c) ? 
                    New String[]{} : 
                    settings.Allowed_Profiles_abv__c.split(',');

Basically the ? is the true part and the : is the false part.

If the settings.Allowed_Profiles_abv__c is blank or null it will simply return a new List<String> otherwise it will split it as needed

Or to keep all your code exactly (adding the ternary to the String instantiation) you could do this

Abbvie_Custom_Settings__c settings = Abbvie_Custom_Settings__c.getInstance('Main');
String  AllowedProfiles= settings == null || settings.Allowed_Profiles_abv__c == null ? '' : settings.Allowed_Profiles_abv__c;

string[] part;
String profile='';
part = AllowedProfiles.split(',');  
  • 2
    settings might also be null... – sfdcfox May 30 '17 at 16:17
  • @sfdcfox - Good point. updated – Eric May 30 '17 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.