Exception Handling¶
Genel Bakış¶
Exception handling, program çalışırken oluşabilecek beklenmedik durumları yönetmek için kullanılan bir mekanizmadır. C#'ta try-catch-finally blokları kullanılarak exception'lar yakalanır ve uygun şekilde işlenir.
Temel Kavramlar¶
- Exception Türleri
- System.Exception (Tüm exception'ların temel sınıfı)
- System.ArgumentException
- System.ArgumentNullException
- System.IndexOutOfRangeException
- System.NullReferenceException
- System.DivideByZeroException
- System.IO.IOException
-
System.FormatException
-
Try-Catch-Finally Blokları
try { // Riskli kod } catch (SpecificException ex) { // Spesifik exception'ı yakala } catch (Exception ex) { // Genel exception'ı yakala } finally { // Her durumda çalışacak kod }
-
Exception Properties
- Message: Hata mesajı
- StackTrace: Hata oluştuğu yığın izi
- InnerException: İç exception
- Source: Hatanın kaynağı
- HelpLink: Yardım linki
Best Practices¶
-
Spesifik Exception'ları Yakalama
try { int.Parse("abc"); } catch (FormatException ex) { Console.WriteLine("Geçersiz sayı formatı"); }
-
Exception Filtreleme
try { // Kod } catch (Exception ex) when (ex.Message.Contains("specific")) { // Filtrelenmiş exception }
-
Custom Exception Oluşturma
public class CustomException : Exception { public CustomException(string message) : base(message) { } public CustomException(string message, Exception inner) : base(message, inner) { } }
-
Exception Loglama
try { // Kod } catch (Exception ex) { LogError(ex); throw; // Exception'ı yeniden fırlat }
Örnek Senaryolar¶
-
Dosya İşlemleri
try { using (StreamReader reader = new StreamReader("file.txt")) { string content = reader.ReadToEnd(); } } catch (FileNotFoundException ex) { Console.WriteLine("Dosya bulunamadı"); } catch (IOException ex) { Console.WriteLine("Dosya okuma hatası"); }
-
Veritabanı İşlemleri
try { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Veritabanı işlemleri } } catch (SqlException ex) { Console.WriteLine("Veritabanı hatası: " + ex.Message); }
-
Web İstekleri
try { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); } } catch (HttpRequestException ex) { Console.WriteLine("HTTP isteği başarısız: " + ex.Message); }
Exception Handling Stratejileri¶
- Fail-Fast
- Hataları erken yakala
- Uygulama durumunu koru
-
Detaylı hata mesajları sağla
-
Graceful Degradation
- Alternatif yollar sun
- Kullanıcıya bilgi ver
-
Uygulamayı çalışır durumda tut
-
Retry Pattern
public async Task<T> RetryOperation<T>(Func<Task<T>> operation, int maxRetries = 3) { for (int i = 0; i < maxRetries; i++) { try { return await operation(); } catch (Exception ex) when (i < maxRetries - 1) { await Task.Delay(1000 * (i + 1)); } } throw new Exception("Maksimum deneme sayısına ulaşıldı"); }
Hata Ayıklama İpuçları¶
-
Debug Modunda Exception'ları Yakalama
#if DEBUG try { // Kod } catch (Exception ex) { Debug.WriteLine($"Hata: {ex.Message}"); throw; } #endif
-
Exception Breakpoints
- Visual Studio'da belirli exception'lar için breakpoint ayarla
-
Exception oluştuğunda debugger'ı durdur
-
Exception Details
catch (Exception ex) { Console.WriteLine($"Message: {ex.Message}"); Console.WriteLine($"StackTrace: {ex.StackTrace}"); Console.WriteLine($"Source: {ex.Source}"); if (ex.InnerException != null) { Console.WriteLine($"InnerException: {ex.InnerException.Message}"); } }
Performans Konuları¶
- Exception Overhead
- Exception'lar pahalıdır
- Sık kullanılan yollarda exception kullanmaktan kaçın
-
TryParse gibi alternatifleri tercih et
-
Exception Pooling
private static readonly ExceptionPool<CustomException> _exceptionPool = new ExceptionPool<CustomException>(); public static CustomException GetException(string message) { return _exceptionPool.GetOrCreate(() => new CustomException(message)); }
Güvenlik Konuları¶
- Exception Information Exposure
- Production'da detaylı hata mesajları gösterme
- Hassas bilgileri loglama
-
Stack trace'i kullanıcıya gösterme
-
Exception Handling in Web Applications
public class GlobalExceptionHandler : IExceptionHandler { public async Task HandleExceptionAsync(ExceptionContext context) { var response = new ErrorResponse { Message = "Bir hata oluştu", ErrorId = Guid.NewGuid().ToString() }; context.Result = new ObjectResult(response) { StatusCode = 500 }; // Log the actual exception LogError(context.Exception, response.ErrorId); } }
Mülakat Soruları¶
- Exception Temelleri
- Exception nedir ve ne zaman kullanılır?
- Checked ve unchecked exception'lar arasındaki fark nedir?
-
Exception handling'in avantajları ve dezavantajları nelerdir?
-
Exception Hiyerarşisi
- System.Exception sınıfının özellikleri nelerdir?
- Custom exception nasıl oluşturulur?
-
Exception inheritance hiyerarşisi nasıl tasarlanmalıdır?
-
Try-Catch-Finally
- Try-catch-finally bloklarının çalışma sırası nasıldır?
- Multiple catch blokları nasıl sıralanmalıdır?
-
Finally bloğu ne zaman kullanılmalıdır?
-
Exception Filtreleme
- Exception filtreleme nedir ve nasıl kullanılır?
- When anahtar kelimesi ne işe yarar?
-
Exception filtrelemenin performans etkisi nedir?
-
Exception Best Practices
- Exception'lar ne zaman yakalanmalıdır?
- Exception'lar ne zaman yeniden fırlatılmalıdır?
-
Exception mesajları nasıl yazılmalıdır?
-
Exception Logging
- Exception'lar nasıl loglanmalıdır?
- Loglama stratejileri nelerdir?
-
Sensitive bilgiler exception'larda nasıl korunur?
-
Exception ve Performans
- Exception handling'in performans maliyeti nedir?
- Exception'lar ne zaman kullanılmamalıdır?
-
Exception pooling nedir ve nasıl kullanılır?
-
Exception ve Güvenlik
- Exception'lar güvenlik açıklarına nasıl yol açabilir?
- Production ortamında exception detayları nasıl yönetilmelidir?
-
Exception'lar SQL injection'a nasıl yol açabilir?
-
Global Exception Handling
- Global exception handler nasıl implemente edilir?
- Web uygulamalarında exception handling nasıl yapılır?
-
API'lerde exception'lar nasıl yönetilmelidir?
-
Exception ve Asenkron Programlama
- Async/await ile exception handling nasıl yapılır?
- Task exception'ları nasıl yönetilir?
- AggregateException nedir ve nasıl kullanılır?
Örnek Kod Soruları¶
-
Custom Exception Oluşturma
public class ValidationException : Exception { // Implementasyon }
-
Exception Filtreleme
try { // Kod } catch (Exception ex) when (ex.Message.Contains("specific")) { // Implementasyon }
-
Global Exception Handler
public class GlobalExceptionHandler : IExceptionHandler { // Implementasyon }
-
Retry Pattern
public async Task<T> RetryOperation<T>(Func<Task<T>> operation, int maxRetries) { // Implementasyon }
-
Exception Logging
public void LogException(Exception ex, string context) { // Implementasyon }