Skip to content

Fix Rethrowing exception variable dereferenced variable may be null#328

Open
odaysec wants to merge 2 commits intomicrosoft:mainfrom
odaysec:patch-1
Open

Fix Rethrowing exception variable dereferenced variable may be null#328
odaysec wants to merge 2 commits intomicrosoft:mainfrom
odaysec:patch-1

Conversation

@odaysec
Copy link

@odaysec odaysec commented Feb 26, 2026

fix keep the existing exception handling behavior but change the rethrow to preserve the original stack trace. In C#, that means using a bare throw; instead of throw ex; inside a catch block. We should not change the control flow or the cancellation logic, only the way the exception is rethrown. No new methods or imports are needed.

Concretely, in samples/electron-winml/winMlAddon/chatClient.cs, locate the catch (Exception ex) block around lines 72–77. Replace throw ex; on line 76 with throw;. Everything else in the method remains unchanged; this preserves the original exception (including stack) while still propagating it when the token has not been cancelled.


Rethrowing an exception variable will lose the stack trace in the original exception, and replace it with the stack trace from the throw statement. This will make debugging the root cause of the exception more difficult, for example if the stack trace is written to a log file. This shows an exception handler which sets the status to UnexpectedException if an exception is thrown. However it throws ex which discards the original stack trace containing the source of the error.

try
{
  Run();
status = Status.Success;
}
catch (Exception ex)
{
  status = Status.UnexpectedException;
  throw ex;    
}

The fix is to replace the throw statement as follows:

try
{
  Run();
status = Status.Success;
}
catch
{
  status = Status.UnexpectedException;
  throw;    
}

Since the variable ex is no longer needed, the catch variable has been removed.

References

MSDN Creating and Throwing Exceptions (C# Programming Guide)
MSDN throw (C# Reference)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants