Exit Code When Unhandled Exception Terminates Exec

2019-02-17 14:12发布

问题:

When a C# .Net console application terminates due to an unhandled exception, are there rules determining which exit code is returned or is 255 always used?

I haven't been able to find documentation on this. A simple console app that executes throw new Exception() dies with exit code 255. I'd like to know if it's safe to assume that all unhandled exceptions will return this same error code or if there are variations/corner cases I need to be aware of.

C:\Temp\> ThrowsExceptionConsoleApp.exe
C:\Temp\> echo %errorlevel%
255

回答1:

No, not always. 255 is a Unix number, normally produced by exiting with -1, unclear how you got to see that. On Windows, a .NET process normally exits with the SEH exception code value, the one that got the process to crash and terminate. Usually -532462766 (aka 0xE0434352) for a managed exception. Last 3 hex pairs spell "CCR", an acronym whose meaning is lost in the fog of time, declared as EXCEPTION_COMPLUS in corexcep.h. Sample question is here.

A well behaved program subscribes AppDomain.CurrentDomain.UnhandledException and provides a better exit code when it calls Environment.Exit(), like the one produced by Marshal.GetHRForException(). You'll get an exit code that matches the managed exception type, values for standard exception types are documented in the CorError.h SDK file.


 echo %errorlevel%

It did not see that in the question before. %errorlevel% can only have a value between 0 and 255, a restriction that goes back to the MS-Dos days. Since the SEH exception code will always be larger, you'd normally always see 255. Only sane way to use %errorlevel% is to assume the program failed when it is not 0. Unless you got specific documentation from the program author.