-
Notifications
You must be signed in to change notification settings - Fork 5.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Exception handling default for top-level statements #25607
Comments
Top-level statements don't do anything special regarding exceptions. All they do is wrapping your code inside a class inside a method that is marked as the main method of the program. Though I don't know anything about the behavior you're describing. As far as I can tell, |
Here is my quick tests on different online compilers, one of them is .NET 5 other is dotnet v2: https://dotnetfiddle.net/PQqZO6 EDIT: It can be beneficient to provide code here as well using System;
public class Program
{
public static void Main()
{
try
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Console.WriteLine("UNCAUGHT " + (e.IsTerminating ? "TERMINATING" : ""));
throw new Exception("GO");
}
//uncomment following line for finally to work
//catch{}
finally
{
Console.WriteLine("FINALLY");
}
}
} |
Interesting, though I only see this behavior on Linux, not on Windows. And yes, it's the same with top-level statements. This code: using System;
try
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Console.WriteLine("UNCAUGHT " + (e.IsTerminating ? "TERMINATING" : ""));
throw new Exception("GO");
}
finally
{
Console.WriteLine("FINALLY");
} Produces:
|
This behaviour is default for the C++ compilers that I know of (MSVC, GCC, clang) unless you specify as a compiler flag. That is, for any thread I tend to put a root try-catch block to make RAII to work efficiently. Similarly, since unwinding and finally does not work, So, interprocess communication or stateful service communication (some OS resources?) may not be shutdown gracefully and the documentation should reflect this accordingly. |
Thanks for this discussion. As @svick points out, top level statements don't change the already defined behavior. That's worth stating in this article. |
With .NET Core and also .NET 5 runtime, the default for stack-rewind on the main thread is, when the exception occurs the runtime does not rewind and your application crashes. Only thing you may get is an event trigger for uncaught exceptions from
AppDomain
.What is the default exception handling for Top-level statements? Does it inject a
try-catch
block, so the stack unwinding occurs and we get our finally blocks working? Or, does it ignore everything about exception handling?Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
Associated WorkItem - 345704
The text was updated successfully, but these errors were encountered: