Search code examples
c#console-applicationexit-code.net-core-3.1

Environment.ExitCode not respected when Main throws exception. How to return nonzero exitcode as well as throwing exception?


// Net core 3.1 Console application
class Program
{
   public static void Main()
   {
      Environment.ExitCode = 1;
      throw new Exception("boom");
   }
}

The above code results in exit code 0!

I expected it to be 1.

https://learn.microsoft.com/en-us/dotnet/api/system.environment.exitcode?view=netcore-3.1 says "Gets or sets the exit code of the process.". Furthermore, "If the Main method returns void, you can use this property to set the exit code that will be returned to the calling environment."

If I remove the exception throw, the exit code is 1 as expected.

I thought the very point of Environment.ExitCode was to specify an exit code that will be used unless the program reaches a point where it is set otherwise.

How can I make sure the exit code is nonzero. while still not needing to catch all exceptions? I want the exception to actually be thrown together with a nonzero exit code because the environment could use it to display a relevant error message.

Do I really need to choose between catching any and all exceptions (going as far as adding a handler for AppDomain.CurrentDomain.UnhandledException), or being able to return an exit code of my choice?


Solution

  • I also made an issue here https://github.com/dotnet/runtime/issues/35599. It was pointed out that the exit code 0 seems like a visual studio specific thing. It outputs nonzero in a normal environment. However, the custom Environment.ExitCode is still not used in case of exception. Exception handling is OS specific - the important thing is that a nonzero code should indeed be returned on exception in prod. The behavior of Environment.ExitCode is intentionally to not be used on exception.