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
EasyMake the tracker fail the way command-line tools do: a message on stderr and exit code 1.
- Add
return 0;as the last line ofProgram.cs. - At the start of the
addcase, whenargs.Length < 3, writeUsage: add <name> <amount>withConsole.Error.WriteLineandreturn 1;. Todaydotnet run -- add Lunchcrashes, becauseargs[2]does not exist. - Write
Invalid amount: abcwithConsole.Error.WriteLine, and replace itsbreak;withreturn 1;. - Do the same in the
defaultcase:Unknown command: flygoes to stderr and the program returns1. Added Lunch: 12.50stays on stdout, and that run exits with0.
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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.