C# Exceptions
Compute a fallible value before printing success and catch only the failure this boundary understands.
How it works
Exceptions report that an operation could not fulfil its contract. A try/catch boundary should recover, add useful context or translate the failure into the caller’s error model. Catching every exception and continuing can hide programming defects. finally performs cleanup on ordinary exits from the try structure, while using is normally clearer for owned IDisposable resources. A thrown exception does not automatically reverse previously committed external effects or every partial mutation.
Run it locally
Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.
dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-buildUse the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.
Example
using System;
internal static class Program
{
private static void Main(string[] args)
{
try
{
int capacity = CapacityFor(-1);
Console.WriteLine($"Capacity: {capacity}");
}
catch (ArgumentException error) { Console.WriteLine($"Rejected: {error.Message}"); }
}
internal static int CapacityFor(int requested)
{
if (requested <= 0) throw new ArgumentException("Positive capacity required");
return requested;
}
}
Expected result
Rejected: Positive capacity required
The negative value throws before a success prefix is printed, leaving one complete rejection message. The catch understands a domain argument failure. Use throw; when rethrowing the same exception so its original stack context is preserved. A public web or file boundary should avoid exposing private paths and implementation details in a user-facing message.
Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.