dimanche 18 juillet 2021

if != null and catch (NullReferenceException ex) { } fail to catch NullReferenceException

I've got a weird one for you guys.

I have a xamarin forms application that gets an image and additional data from a server to be assigned to a properties in a viewmodel which are bound to an and a in the page xml. I've always had the server running, therefore images were always provided, and it worked as intended.

Pamela implements IEsther and so does EmotionalSolutions type, but they are not the same type. (IEsther represents the data, Pamela the Data and the image)

try
{
    Refresh();
    Pamela pamela = await ConnectionManager.Standard.GetSinglePamelaAsync();
    if (pamela != null) 
    {
        ***DataSolution = pamela;***
    }
                
    ImageToRate = ImageSource.FromStream(() => new MemoryStream(pamela.Image));

    OnPropertyChanged("ImageToRate");
}
catch (System.NullReferenceException) { }

Stars to mark where the exception occurs.

Now I didn't have the server running for once and it crashes on DataSolution = pamela on a System.NullReferenceException. Debugging shows, that at the time of the if clause, pamela is null! and it continues! into the if clause causing it to throw a System.NullReferenceException that is not caught by the catch block!.

I'm out of ideas on that one.

It is not important if it is null or not to me, I don't care if the page remains empty. I just want it to execute without crashing on that page.

I'll try setting it to if (false) and check if it is generally passing on false. Also I'll add an else to check if it is executing both.

The Error text: System.NullReferenceException: "Object reference not set to an instance of an object.", "this.pamela" was "null"

There is no variable or property pamela at class level, you have seen all uses of the name "pamela" in the whole document in the above snippet.

The IDE and compiler used is Visual Studio 2019 Community Edition 2.11.13.53049.

How do I get it running?

Aucun commentaire:

Enregistrer un commentaire