[SOLVED] How to handle Resources.Load file not found NullReferenceException

So I have the following code which works fine when the text file is present:

TextAsset localTextFile = (TextAsset)Resources.Load("MyTextFile", typeof(TextAsset)); //MyTextFile.txt is present in Assets/Resources folder
   
if (string.IsNullOrEmpty(localTextFile.text)) {
    Debug.Log("Error: file empty or null\n");
} else {
    Debug.Log(localTextFile.text);
}

When the file is present, it succesfully goes to Debug.Log(localTextFile.text); line.

Now if I change MyTextFile to a non-existent filename, instead of getting the Debug.Log("Error: file empty or null\n"); line, I get the following error:

NullReferenceException: Object reference not set to an instance of an object

How can I handle this NullReferenceException properly?

If the relevant data, and ends the program, otherwise to be ignored in the logic.

if(localTextFile != null)
{
ProcessLogic(localTextFile );
}

@nicecapj Thank you, this helped me understand the problem.

You cannot use string.IsNullOrEmpty to test either localTextFile.text or localTextFile.

But you can test localTestFile against null. So my corrected code is:

TextAsset localTextFile = (TextAsset)Resources.Load("MyTextFile", typeof(TextAsset)); //MyTextFile.txt is present in Assets/Resources folder
      
if (localTextFile == null) {
    Debug.Log("Error: file null or missing\n");
} else {
    Debug.Log(localTextFile.text);
}