C# Exceptions

try, catch, finally and throw.

✍️ 2 exercises in this lesson
  • try { } catch (SpecificException ex) { } finally { }
  • throw new InvalidOperationException("message");
  • Exception filters: catch (Exception ex) when (ex.Message.Contains("x"))
  • Custom exceptions inherit from Exception.
  • using statements dispose resources automatically.

Key Takeaways: C# Exceptions

Mastering C# Exceptions helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C# Exceptions Code Example

C#
static decimal Withdraw(decimal balance, decimal amount)
{
    if (amount > balance) throw new InvalidOperationException("Insufficient balance");
    return balance - amount;
}

try
{
    Console.WriteLine(Withdraw(5000, 2000));
    Console.WriteLine(Withdraw(5000, 9000));
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}
finally
{
    Console.WriteLine("Done");
}

try { int.Parse("abc"); }
catch (FormatException) { Console.WriteLine("Not a number"); }
Output
3000
Error: Insufficient balance
Done
Not a number
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C# Exceptions Practice Exercises

Check what you learned in “C# Exceptions”.

/ 2 solved
Fill in the blank

Throw an exception.

 new InvalidOperationException("Insufficient balance");
✓ Correct! Not quite. Try again.
Multiple choice

What does a using statement do?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services