Using the System.Text.Json library, I have a JsonNode from which I am extracting some data, which may or may not be null. For now, I have wrapped the code in a try-catch block instead of testing each element for being null, but I noticed some seemingly odd behaviour when one of the elements was null: the code would crash with a "NullReferenceException", despite that exception being included in the catch block (or when the catch block was set to handle Exception itself), but only when using the IDE (Visual Studio 2019)'s debugger.
Dummy code to reproduce the behaviour:
using System.Text.Json;
using System.Text.Json.Nodes;
...
string s = "{\"People\":[{\"Name\":\"Bob\",\"Age\":60},{\"Name\":\"Carl\",\"Age\":null}]}";
JsonNode n = JsonNode.Parse(s)["People"];
try { n[1]["Age"].ToJsonString(); } catch (Exception ex) { MessageBox.Show($"Caught Exception {ex.Message}"); }
If I run the debugger, the execution breaks with a NullReferenceException upon reaching that line.
If I do any of the following, the exception is successfully caught:
- run the debugger with the deprecated "Use Managed Compatability Mode" setting enabled
- execute the program outside of the IDE
- run the same code in the interactive console
While just testing for null works to avoid the issue in this case, I'd like to know what's going on for future reference in case it occurs in a more complicated situation. Does anyone have an explanation as to what's causing the exception to not be caught in the debugging context, and whether there is a (non-deprecated) setting that can be changed (or other workaround/solution) to avoid the issue in future?
Quick note: When VS breaks during your exception, you can simply hit Run (or F5) to continue and the handler will be triggered as normal.
There are a number of Exceptions that are set to "break when thrown" while debugging in VS. There are a couple of ways to disable them.
In the exception popup, expand the little "Exception Settings" section in the dialog. It should give you options to disable "Break when this exception type is thrown".
You can bring up the full list in the Exception Settings window: Debug > Windows > Exception Settings.
Under "Common Language Runtime Exceptions" there should be a number of items ticked, including
System.NullReferenceExceptionin your system (unless you disabled it with the previous method). Feel free to un-tick the ones you don't want, or tick the ones you want VS to forcibly break on (to give you a chance to analyse the code when they're thrown).