Menu
CoddyTech

Exit Codes

Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 5 of 20.

When a program ends it hands an exit code to whatever started it: 0 means it worked, anything else means it failed. Scripts and build servers read that number. Top-level statements set it with return. Once one return gives a number, every path must end with one, so the last line becomes return 0;. Without it the compiler reports error CS0161.

Errors go to the second output stream, stderr, with Console.Error.WriteLine. Normal output stays on stdout, so someone who saves the output to a file still sees the errors.

if (args.Length != 1)
{
    Console.Error.WriteLine("Usage: greet <name>");
    return 1;
}
Console.WriteLine($"Hello, {args[0]}!");
return 0;
challenge icon

Challenge

Easy

Make the tracker fail the way command-line tools do: a message on stderr and exit code 1.

  1. Add return 0; as the last line of Program.cs.
  2. At the start of the add case, when args.Length < 3, write Usage: add <name> <amount> with Console.Error.WriteLine and return 1;. Today dotnet run -- add Lunch crashes, because args[2] does not exist.
  3. Write Invalid amount: abc with Console.Error.WriteLine, and replace its break; with return 1;.
  4. Do the same in the default case: Unknown command: fly goes to stderr and the program returns 1.
  5. Added Lunch: 12.50 stays on stdout, and that run exits with 0.

Try it: the terminal beside the editor already reads dotnet run -- add Lunch, so Run shows Usage: add <name> <amount> in red, because it went to stderr, instead of a crash. Add 12.50 to the arguments and Run again: Added Lunch: 12.50. The terminal does not show exit codes, so Check reads them: add Lunch abc and fly must exit with 1, and add Lunch 12.50 with 0.

Try it yourself

using System.Globalization;

var count = 0;
var total = 0m;

if (args.Length == 0)
{
    Console.WriteLine("Expense Tracker");
    Console.WriteLine($"{count} expenses");
    Console.WriteLine($"Total: {total:F2}");
}
else
{
    switch (args[0])
    {
        case "add":
            if (!decimal.TryParse(args[2], CultureInfo.InvariantCulture, out var amount))
            {
                Console.WriteLine($"Invalid amount: {args[2]}");
                break;
            }
            Console.WriteLine($"Added {args[1]}: {amount:F2}");
            break;
        default:
            Console.WriteLine($"Unknown command: {args[0]}");
            break;
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C# and .NET Basics