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.
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);
}
}
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