BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

Exiting a Program with an Error Code

When a program exits, it is common to return an integer value to indicate the closing state. If the program closed normally, this value is generally zero. Other values usually provide error codes that allow the caller to identify problems.

Exit Codes

When you create software that is designed to be called by other programs, you might decide to return an integer exit code. This is particularly common for console applications that might be called from the command line or from a batch file. Conventionally, returning an exit code of zero indicates that the program ran correctly and exited without error. All other values generally designate error codes. These can be examined by the calling program or script, so that appropriate recovery actions can be taken.

To return an exit code you simply need to set the value of a static property of the Environment class. The property in question is ExitCode. As the value of ExitCode defaults to zero, you would normally only change it to indicate a failure state.

To demonstrate, create a new console application project named, "ExitCodeDemo". Replace the automatically generated Main method with the code shown below. This creates a program that receives an integer value via a command line argument. If the value can be converted to an integer, it is incremented and the result is applied to the ExitCode property before the program stops.

static void Main(string[] args)
{
    int exitCode = 0;
    bool ok = args.Length > 0 && int.TryParse(args[0], out exitCode);
    Environment.ExitCode = exitCode + 1;
}

Save the project and build it to generate an executable file. Once compiled, you can close Visual Studio. We'll now create a batch file that calls the .NET program and reads the exit code. Create a new text file using Notepad or a similar text editor. Add the following script commands to the file:

@echo off
ExitCodeDemo 99
echo The exit code was %ERRORLEVEL%.

The script calls the console application executable, passing the value 99. We should, therefore, expect the program to quit with an exit code of 100. This code is extracted using the %ERRORLEVEL% value in the final line. Save the batch file within the same folder as the compiled executable, naming the file, "ExitDemo.bat". Make sure that the text editor does not add any other file name extension

Testing the Exit Code

You can now try running the batch file to check the result. Open a new command prompt window and change directory to the folder containing the batch file and executable. Launch the batch file by typing the following command and pressing Enter.

ExitDemo

The batch file launches the executable and displays a message containing the exit code. The result should appear as follows:

The exit code was 100.
20 November 2013