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.
CatchFormatException
,ArgumentException
, etc., not justException
. -
Clean up with
finally
.
Usefinally
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!