Exception Handling
Things go wrong at runtime: a file is missing, a network call times out, a user types letters into a number field. Exceptions let you handle that without crashing the whole program.
try
{
int[] scores = { 90, 85, 77 };
Console.WriteLine(scores[5]); // out of range
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Invalid index: {ex.Message}");
}
finally
{
Console.WriteLine("Always runs, whether or not an exception happened.");
}
The pieces
trywraps code that might throw.catch (SomeException ex)runs if that exception type (or a subclass of it) is thrown inside thetryblock, you can stack multiplecatchblocks for different exception types.finallyruns no matter what, whether thetrysucceeded, threw, or the catch itself re-threw, use it for cleanup (closing a file, releasing a resource).throwraises an exception yourself:throw new ArgumentException("amount must be positive");.
Custom exceptions
class InsufficientXpException : Exception
{
public InsufficientXpException(string message) : base(message) { }
}
if (xp < required)
throw new InsufficientXpException($"Need {required} XP, only have {xp}.");
A custom exception inherits from Exception (or a more specific built-in one) and gives calling code something precise to catch, instead of catching the broad, generic Exception.