C# exception yapısı, exception fırlatmak ve throw ile throw ex farkı
 
Bu yazida, iç içe metodlarda exception yönetimi ve throw kullanimina deginecegim.

Bir metodumuz olsun try ve catch blogu olsun ve bu metod içerisinde bir baska metod da çagirilsin.

Çagirilan metodda da try catch olsun. Çagrilan method ve ana metod da ikisinde de çalisma aninda ortaya çikacak bir hata olsun. Bu durumda ben içerdeki metodun hatasini görmek istersem ne yapmam gerekir?

Normal yapida: Asagidaki örnek üzerinden gidelim Index ana method olsun ve içerisinde GetName çagrilan metod olsun.
 
        public ActionResult Index()
        {
            try
            {
                GetName();
                Dictionary dList = new Dictionary();
                dList.Add(1, 3);
                dList.Add(1, 4);
            }
            catch (Exception ex)
            {
                TempData["Result"] = ex.Message;
            }
            return View();
        }


        public int GetName()
        {
            string message = string.Empty;
            int id =0;
            try
            {
                id = Convert.ToInt32("Numara");
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return id;
        }

Index metodunu isletiyoruz ilk olarak GetName() metoduna giriyor ve burada "Numara" kelimesi int tipine çevrilmek isteniyor çevrilemedginden hata veriyor ve catch bloguna düsüyor.

GetName() metodunun catch blogunda ise hata message adli bir degiskene yaziliyor. Herhangi bir hata firlatma yok henüz ve try catch ile de kontrol alindigindan metod isletime devam ediliyor. Daha sonra Index metodu devam ediliyor ve dList dictionary'sine ayni keyden ikinci kayit eklenmek istediginde hata firlatiyor yine catch bloguna düsüyor.

Index metodunun catch bloganda ex.Message bize dictionary hatasini gösterir. Fakat biz ilk hata olan GetName() metodunun hatasini görmek istiyorsak bu noktada exception firlatmaliyiz.

"throw" kelimesi türkçe olarak "firlatmak, atmak" anlamina gelmektedir. Bu kelime ile exception firlatilir.
Simdi metodu biraz düzenleyelim. GetName() metodunun catch bloguna throw ex ekleyelim. Asagidaki gibi,
 

        public ActionResult Index()
        {
            try
            {
                GetName();
                Dictionary dList = new Dictionary();
                dList.Add(1, 3);
                dList.Add(1, 4);
            }
            catch (Exception ex)
            {
                TempData["Result"] = ex.Message;
            }
            return View();
        }


        public int GetName()
        {
            string message = string.Empty;
            int id =0;
            try
            {
                id = Convert.ToInt32("Numara");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return id;
        }
Bu sekilde çalistirildiginda Index metodundaki TempData["Result"]’a dictionary hatasi degilde Convert.ToInt32 deki hata yazilir.
Çünkü içteki metod throw ex; ile exception firlatiyor. throw ex geldigi ana GetName() metodunda çikiyor bir üsttetki metodun yani Index metodunun catch bloguna geliyor. Ve ilgili hata oraya tasinmis olunuyor.

Dikkat ettiysek hata aldigi an üstteki metodun catch bloguna girer üstteki blogun devamindaki kodlar isletilmez. Burada önemli bir konu vardir.
throw ex; yerine throw; da kullanabilirdik.

throw ile throw ex farki 

Burada throw ex; ile throw; arasindaki hata tasima farki ise ex.Message yani mesaj yazisi degismiyor ayni hata yazisidir. Ama ex.StackTrace adli özelligi farkli oluyor.

throw ex :
Bir üstteki metodun exception'una girdiginde yeniden exception olusturur. Exception mesaji bir öncekinin aynisi kalir ama StackTrace degisir. StackTrace söle degisir detayi azaltilir. Yalnizca hata alinan metod ve bir önceki hatanin geldigi metod gösterilir. Daha öncesi ve detayini göstermez.

throw:
Hatayi genisleterek tasir. Ilk StackTrace tam kalacak sekilde bir üsttekinin catch blogunda kendi StackTrace'i + su anki metodun yerini gösteren StackTrace ekleyerek yukari tasir. Böylece hata yeri detaylica en sondaki catch bloguna dogru tasinir. Yani throw kullanmak daha avantajlidir. Throw ex; her firlattigi catch de yeniden olusturuluyor. Throw ise var olan tasiniyor.

C# .net exception yapisi bu sekildedir. Metodlar ile alistirma yaparak konuyu daha iyi irdeleyebilirsiniz. 
 

Author: Engin ATALAY
Date: 1.09.2016 18:48:12
View Count: 9063
 
 

COMMENTS
 
Resim Yüklenemedi
5
22 Haziran 2021 02:47
5
 
 
 
 
 
 
 
 
 
 
 
 
WRITE COMMENT
 
 
Your Name :
 
 
 
E-mail :
 
 
 
Your Message :
 
 
 
 
 
 
 
This project : ASP.NET MVC , RAZOR, Entity Framework , CSS , HTML , JQUERY(2.0.2) , AJAX the C# side-tier architecture was developed with logic.
 
Yukarı Çık