Xamarin iOS Try Catch blocks crash app instead of catching

Joshua Tanton 1 Reputation point
2021-04-12T17:54:25.013+00:00

I have been debugging an issue on my Xamarin iOS application. I noticed that instead of hitting a catch on a try catch block. the App just shuts down. I'm not sure when this started happening as this is the first time I have noticed this.

But now I've put the following code in multiple spots in my application. No matter what happens, when this code is hit a null reference exception crashes the app and does not get caught by the catch. This is true both when using a general catch or a specific crash (NullReferenceException).

string testers = "";
CustomObject test = null;
try
{
testers = test.property;
}
catch (Exception e)
{
testers = "fail";
}

When debugging this the attempt to access the property fails and the app immediately shuts down. The catch statement is not triggered. I have put this in multiple places in my app. I have no idea why it isn't being caught. There are multiple points where I use try catches to prevent failures in the app. It would be appreciated if someone could explain this, or give me some ideas on how to prevent this.

I should note, this is Xamarin iOS code not Xamarin.Forms.

Thanks,

Update
This code does function correctly (not crash) when I place it within my AppDelegate.cs FinishedLaunching method. I'm not sure why but maybe there is a way to get it working in other parts of the app (e.g., viewcontrollers)

Update 2
I've noticed if I replace the code attempting to access a property of null object with "throw new NullReferenceException();" The catch will trigger. Of coarse this isn't very helpful to me.

Developer technologies .NET Xamarin
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,756 Reputation points
    2021-04-13T04:12:23.283+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Could you provide more information ?

    What's the version of Xamarin.iOS you're using ?
    What's the simulator/real device did you test on ?

    ---

    Since I test with Xamarin.iOS 14.14.2.5 and test on simulator iPhone 12 , everything works fine .

    No matter I place the code in AppDelegate or ViewController , the exception was caught as expected .

    Could you try replace Exception with NullReferenceException ?

    Or just use testers = test?.property; instead of placing it into try catch .


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.