Lesson 31 of 34 · LINQ & Errors
C# Exceptions: try, catch, finally and Custom Exceptions
Things go wrong: a file is missing, a user types abc where a number belongs, a hero tries to buy a sword they cannot afford. C# reports such problems with exceptions — objects that describe the error and travel up the call stack until some code catches them. If nobody does, the program crashes with the message you have seen in earlier lessons.
try and catch
try
{
int level = int.Parse("forty");
Console.WriteLine(level);
}
catch (FormatException ex)
{
Console.WriteLine($"Not a number: {ex.Message}");
}
When a statement inside try throws, the rest of the try block is skipped and the first matching catch runs. Catch specific exception types: a bare catch (Exception) also swallows bugs you would rather see. You can stack several catch blocks — the most specific first — and add a condition with when:
catch (ArgumentException ex) when (ex.ParamName == "price") { /* ... */ }
finally
A finally block runs whether or not an exception happened — perfect for cleanup:
try
{
Console.WriteLine("Opening the vault");
throw new InvalidOperationException("The lock is jammed");
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Closing the vault"); // always runs
}
Throwing exceptions
Your own methods should throw when they are called with arguments that make no sense:
public static double Divide(double a, double b)
{
if (b == 0)
{
throw new ArgumentException("Cannot divide by zero.", nameof(b));
}
return a / b;
}
Pick a fitting built-in type: ArgumentException (bad argument), ArgumentOutOfRangeException (value outside the allowed range), ArgumentNullException, InvalidOperationException (the object is not in a state that allows the call), KeyNotFoundException, NotImplementedException.
Inside a catch, throw; rethrows the same exception without losing its stack trace.
Custom exceptions
When callers need to react to a specific problem, define your own exception type by inheriting from Exception:
public class QuestLockedException : Exception
{
public int RequiredLevel { get; }
public QuestLockedException(int requiredLevel)
: base($"This quest requires level {requiredLevel}.")
{
RequiredLevel = requiredLevel;
}
}
Name custom exceptions with the Exception suffix, pass a helpful message to base(...), and add properties for the details callers need.
Exceptions are for exceptional cases
Throwing is slow and makes control flow harder to follow. When failure is an expected outcome — like a user typing bad input — prefer the Try pattern you met in Chapter 2: int.TryParse returns false instead of throwing.
Common mistakes
- Empty catch blocks (
catch { }) hide real bugs. - Catching
Exceptionfirst: later, more specificcatchblocks can never run (the compiler reports an error). - Using exceptions for normal flow — validate with
iforTryParsewhen failure is common.
Assignment
- Complete
InsufficientGoldException: it stores how much gold isMissingand its message is"Not enough gold: missing 20". Shop.Buy(gold, price)returns the gold left after buying. A negative price throwsArgumentOutOfRangeException; not enough gold throwsInsufficientGoldExceptionwith the missing amount.Shop.TryBuy(gold, price)callsBuyand turns the result into a message:"Bought! 30 gold left","Missing 20 gold"or"Invalid price".Shop.ParseOrDefault(text, fallback)returnsint.Parse(text), but catchesFormatExceptionandOverflowExceptionand returnsfallbackinstead.
Premium lesson
Unlock the full Learn C# course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Errors and exceptions in other languages
- JavaScript Error Handling: try, catch and Custom Errors · JavaScript
- Python Exceptions: try, except, else and finally · Python
- Go Error Handling: error Values and if err != nil · Go
- Java Exceptions: try, catch, finally and Custom Exceptions · Java
Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.
Lesson last updated on .