Search code examples
android.netexceptionmauirelease

.NET MAUI Exceptions Not Caught in RELEASE build (Android)


It looks like exceptions thrown under a release build are not caught in exception handling:

Here is code and logs generated when running under a DEBUG build and a RELEASE build:

   try
   {
      Flog.Info("Force exception. Should be caught and logged next...");
      object someObj = null; 
      someObj.GetType();
   }
   catch (Exception e)
   {
      Flog.Error(e); // Log error
   }

Here is the log under RELEASE BUILD:

    [2024-08-26][18:50:01.0863]:INFO:Force an exception. Should be caught and logged next...
    // (and nothing else logged - app crashes)

Under DEBUG...

    [2024-08-26][18:56:07.0897]:INFO:Force exception.  Should be caught and logged next...
    [2024-08-26] 
    [18:56:11.0326]:ERROR:DescriptionModels.DescriptiveText:Object reference not set to an instance of an object....

SO... it is clear that under a RELEASE build exceptions are not caught. WHY IS THIS? Is there a compiler switch of some sort?


MORE INFORMATION AND MINIMAL EXAMPLE:

The link below has a ZIP file with a solution and project that demonstrates this problem.

  1. Run a release build of the project "TestException". You will see two buttons: One that will force a null reference exception and another that starts a background thread that sends a ping request once a second, using thje NetworkInformation.Ping class.

  2. Click on the button to force an exception a few times. You'll see a popup alert reporting the null reference when the exception is caught.

  3. Then click on the button to start the background Ping thread.

  4. Once that thread is started, click on the button to force an exception again. This time, you'll see that the app just abends and quits. The exception handler is never called.

  5. NOTE: The background thread does not have to be running for this problem to occur: It only needs to run once. If it is run once, then stopped, the problem will still occur if you force the exception again.

Minimal code project to demonstrate the issue

Note that this problem ONLY occurs in RELEASE builds. Debug builds do NOT have this issue.

SO: What is in the Ping class that causes this issue? OR... what is wrong with the code that causes the issue only in release builds?

GitHub Issue Logged Here


ANOTHER UPDATE:

It is not necessary to even run the background thread. Simply calling "Ping" will trigger the issue.



Solution

  • This is not a "solution" but it is indeed an answer.

    The issue here was related to use of the System.Net.NetworkInformation.Ping class. Calling the Ping() method on this class somehow "steals" the exception handling such that subsequent exceptions are not caught - and ONLY in RELEASE builds.

    See this GitHub explanation

    Removing the use of this class solved the problem.

    The underlying issue should be the topic of a different thread.