Skip to content

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

  1. Exception Türleri
  2. System.Exception (Tüm exception'ların temel sınıfı)
  3. System.ArgumentException
  4. System.ArgumentNullException
  5. System.IndexOutOfRangeException
  6. System.NullReferenceException
  7. System.DivideByZeroException
  8. System.IO.IOException
  9. System.FormatException

  10. 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
    }
    

  11. Exception Properties

  12. Message: Hata mesajı
  13. StackTrace: Hata oluştuğu yığın izi
  14. InnerException: İç exception
  15. Source: Hatanın kaynağı
  16. HelpLink: Yardım linki

Best Practices

  1. Spesifik Exception'ları Yakalama

    try
    {
        int.Parse("abc");
    }
    catch (FormatException ex)
    {
        Console.WriteLine("Geçersiz sayı formatı");
    }
    

  2. Exception Filtreleme

    try
    {
        // Kod
    }
    catch (Exception ex) when (ex.Message.Contains("specific"))
    {
        // Filtrelenmiş exception
    }
    

  3. Custom Exception Oluşturma

    public class CustomException : Exception
    {
        public CustomException(string message) : base(message)
        {
        }
    
        public CustomException(string message, Exception inner) 
            : base(message, inner)
        {
        }
    }
    

  4. Exception Loglama

    try
    {
        // Kod
    }
    catch (Exception ex)
    {
        LogError(ex);
        throw; // Exception'ı yeniden fırlat
    }
    

Örnek Senaryolar

  1. 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ı");
    }
    

  2. Veritabanı İşlemleri

    try
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            // Veritabanı işlemleri
        }
    }
    catch (SqlException ex)
    {
        Console.WriteLine("Veritabanı hatası: " + ex.Message);
    }
    

  3. 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

  1. Fail-Fast
  2. Hataları erken yakala
  3. Uygulama durumunu koru
  4. Detaylı hata mesajları sağla

  5. Graceful Degradation

  6. Alternatif yollar sun
  7. Kullanıcıya bilgi ver
  8. Uygulamayı çalışır durumda tut

  9. 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ı

  1. Debug Modunda Exception'ları Yakalama

    #if DEBUG
    try
    {
        // Kod
    }
    catch (Exception ex)
    {
        Debug.WriteLine($"Hata: {ex.Message}");
        throw;
    }
    #endif
    

  2. Exception Breakpoints

  3. Visual Studio'da belirli exception'lar için breakpoint ayarla
  4. Exception oluştuğunda debugger'ı durdur

  5. 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ı

  1. Exception Overhead
  2. Exception'lar pahalıdır
  3. Sık kullanılan yollarda exception kullanmaktan kaçın
  4. TryParse gibi alternatifleri tercih et

  5. 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ı

  1. Exception Information Exposure
  2. Production'da detaylı hata mesajları gösterme
  3. Hassas bilgileri loglama
  4. Stack trace'i kullanıcıya gösterme

  5. 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ı

  1. Exception Temelleri
  2. Exception nedir ve ne zaman kullanılır?
  3. Checked ve unchecked exception'lar arasındaki fark nedir?
  4. Exception handling'in avantajları ve dezavantajları nelerdir?

  5. Exception Hiyerarşisi

  6. System.Exception sınıfının özellikleri nelerdir?
  7. Custom exception nasıl oluşturulur?
  8. Exception inheritance hiyerarşisi nasıl tasarlanmalıdır?

  9. Try-Catch-Finally

  10. Try-catch-finally bloklarının çalışma sırası nasıldır?
  11. Multiple catch blokları nasıl sıralanmalıdır?
  12. Finally bloğu ne zaman kullanılmalıdır?

  13. Exception Filtreleme

  14. Exception filtreleme nedir ve nasıl kullanılır?
  15. When anahtar kelimesi ne işe yarar?
  16. Exception filtrelemenin performans etkisi nedir?

  17. Exception Best Practices

  18. Exception'lar ne zaman yakalanmalıdır?
  19. Exception'lar ne zaman yeniden fırlatılmalıdır?
  20. Exception mesajları nasıl yazılmalıdır?

  21. Exception Logging

  22. Exception'lar nasıl loglanmalıdır?
  23. Loglama stratejileri nelerdir?
  24. Sensitive bilgiler exception'larda nasıl korunur?

  25. Exception ve Performans

  26. Exception handling'in performans maliyeti nedir?
  27. Exception'lar ne zaman kullanılmamalıdır?
  28. Exception pooling nedir ve nasıl kullanılır?

  29. Exception ve Güvenlik

  30. Exception'lar güvenlik açıklarına nasıl yol açabilir?
  31. Production ortamında exception detayları nasıl yönetilmelidir?
  32. Exception'lar SQL injection'a nasıl yol açabilir?

  33. Global Exception Handling

  34. Global exception handler nasıl implemente edilir?
  35. Web uygulamalarında exception handling nasıl yapılır?
  36. API'lerde exception'lar nasıl yönetilmelidir?

  37. 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ı

  1. Custom Exception Oluşturma

    public class ValidationException : Exception
    {
        // Implementasyon
    }
    

  2. Exception Filtreleme

    try
    {
        // Kod
    }
    catch (Exception ex) when (ex.Message.Contains("specific"))
    {
        // Implementasyon
    }
    

  3. Global Exception Handler

    public class GlobalExceptionHandler : IExceptionHandler
    {
        // Implementasyon
    }
    

  4. Retry Pattern

    public async Task<T> RetryOperation<T>(Func<Task<T>> operation, int maxRetries)
    {
        // Implementasyon
    }
    

  5. Exception Logging

    public void LogException(Exception ex, string context)
    {
        // Implementasyon
    }
    

Kaynaklar