Catch Smarter, Not Harder: C# Exception Handling Best Practice
⚠️ Avoid Catching General Exceptions
Catching all exceptions with catch (Exception ex)
might seem convenient, but it can hide real problems and make debugging harder.
Bad:
try
{
// DB operation
dbContext.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong: " + ex.Message);
}
Better
try
{
// DB operation
dbContext.SaveChanges();
}
catch (SqlException ex)
{
Console.WriteLine("Database error: " + ex.Message);
}
Why?
Catching specific exceptions like SqlException, FileNotFoundException, or ArgumentNullException helps you:
Handle errors accurately.
Avoid swallowing bugs unintentionally.
Keep exception handling clean and predictable.