🛡️ Exception Handling = Robust Code
Apps crash without error handling. Try-catch handles errors gracefully. Robust, reliable apps.
📝 Try-Catch Basics
try
{
// Code that might throw
int result = int.Parse(input);
Console.WriteLine($"Result: {result}");
}
catch (FormatException ex)
{
Console.WriteLine($"Invalid format: {ex.Message}");
}
catch (OverflowException ex)
{
Console.WriteLine($"Number too large: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
throw;
}
finally
{
Console.WriteLine("Operation completed");
}
// Using with IDisposable
using (var connection = new SqlConnection(connectionString))
{
// Auto-disposed
}
🎯 Advanced Patterns
// Custom exception
public class ValidationException : Exception
{
public ValidationException(string message) : base(message) { }
public ValidationException(string message, Exception inner) : base(message, inner) { }
}
// Try pattern
public bool TryParseInt(string input, out int result)
{
try
{
result = int.Parse(input);
return true;
}
catch
{
result = 0;
return false;
}
}
// Exception filters
try
{
// Some code
}
catch (Exception ex) when (ex is TimeoutException || ex is SqlException)
{
// Handle specific errors only
}
// Throw with inner exception
try
{
// Some code
}
catch (Exception ex)
{
throw new ApplicationException("Failed to process", ex);
}
// Global exception handling
public class GlobalExceptionHandler
{
public static async Task HandleException(Exception ex, ILogger logger)
{
logger.LogError(ex, "Unhandled exception");
throw ex;
}
}
✅ Exception Tips
- Don’t catch exceptions you can’t handle
- Use specific exception types
- Log all exceptions with context
- Use finally for cleanup
- Use using for IDisposable resources
“Exception handling makes apps robust. Catch, log, recover. Essential for professional C#.”
