16

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
2
  • 3
    Didn't find anything in ECMA-335, so I guess the exit code of the runtime is not standardized for the scenario of an unhandled exception. Commented Feb 9, 2016 at 14:30
  • 3
    Hmm, for me on Windows 10.0.14393, ECHO %ERRORLEVEL% outputs -532462766. Commented Jul 25, 2016 at 16:49

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Seems like the restriction was lifted sometime because in Windows 10.0.14393 I get -532462766 for ECHO %ERRORLEVEL%.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.