Simple diagnostics: exceptions vs guard checks
Apply guard checks for expected invalid inputs, throw exceptions for exceptional states, and use try/catch to handle errors gracefully.
Simple diagnostics: exceptions vs guard checks is a free C# Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Diagnostics overview
Goal: Use guard checks for expected problems and exceptions for rare, serious issues.
Guard check demo
Guard checks return a status instead of throwing for common invalid inputs.
using System;
public class Program
{
public static bool TryDivide(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false; // guard check fails
}
result = a / b;
return true;
}
public static void Main(string[] args)
{
int r;
bool ok = TryDivide(10, 0, out r);
Console.WriteLine("ok=" + ok + " result=" + r);
}
}
Exception demo
Exceptions stop execution unless handled. Use them for unexpected or serious conditions.
using System;
public class Program
{
public static int PriceWithTax(int price, int ratePercent)
{
if (price < 0)
{
throw new ArgumentOutOfRangeException("price");
}
if (ratePercent < 0 || ratePercent > 100)
{
throw new ArgumentOutOfRangeException("ratePercent");
}
return price + (price * ratePercent / 100);
}
public static void Main(string[] args)
{
try
{
int total = PriceWithTax(100, 20);
Console.WriteLine("Total=" + total);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Mixing checks & exceptions
Mix approaches: guard checks for routine validation, exceptions for invalid states.
using System;
public class Program
{
public static bool TryParsePrice(string text, out int value)
{
return int.TryParse(text, out value); // guard check
}
public static int GetDiscount(int code)
{
if (code < 0) throw new ArgumentException("Invalid code"); // exception
return 10;
}
public static void Main(string[] args)
{
int v;
if (TryParsePrice("123", out v))
{
Console.WriteLine("Parsed " + v);
}
try
{
int d = GetDiscount(-1);
Console.WriteLine("Discount=" + d);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
try/catch example
Use try/catch to handle exceptions and keep the program running.
using System;
public class Program
{
public static void Main(string[] args)
{
try
{
int x = 10;
int y = 0;
int z = x / y; // will throw DivideByZeroException
Console.WriteLine(z);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
}
}
Tips
Tips:
- Guard checks return safe defaults for common cases.
- Exceptions should be rare and meaningful.
- Catch only what you can handle.
Guard vs exception
Recap
Recap: Use guard checks for common invalid inputs, throw exceptions for exceptional states, and handle with try/catch when recovery is possible.
Frequently asked questions
Is the “Simple diagnostics: exceptions vs guard checks” lesson free?
Yes — the full text of “Simple diagnostics: exceptions vs guard checks” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Simple diagnostics: exceptions vs guard checks”?
Apply guard checks for expected invalid inputs, throw exceptions for exceptional states, and use try/catch to handle errors gracefully. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Simple diagnostics: exceptions vs guard checks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- if/else, switch (classic), loops: for, while, do, foreach
- break/continue; goto (avoid); scope; exceptions vs guard checks
- Simple diagnostics: exceptions vs guard checks