Exception Best Practices

How (and when) to use exceptions in C#

Posted by Rodrigo Castro on December 3, 2024

Exceptions are powerful, but you should use them wisely.

✅ Best Practices

  • Use exceptions for exceptional cases only.
    Don’t use them for normal control flow.

  • Catch only what you can handle.
    Don’t catch exceptions if you can’t fix the problem.

  • Don’t swallow exceptions.
    Avoid empty catch blocks: always log or report errors.

  • Use specific exception types.
    Catch FormatException, ArgumentException, etc., not just Exception.

  • Clean up with finally.
    Use finally to release resources (like files or database connections).

🚫 What Not to Do

1
2
3
4
5
6
7
8
try
{
    // risky code
}
catch
{
    // nothing here! Don't do this!
}

📝 Sample: Logging the Error

1
2
3
4
5
6
7
8
try
{
    // risky code
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Remember:

  • Plan for errors, but don’t expect them everywhere.
  • Keep your code readable and maintainable.

Next: File I/O basics!