Aytaylik, dasturimizda yosh cheklovi bor: try { Person person = new Person { Name = "Tom", Age = 17 }; } catch (Exception ex) { Console.WriteLine($"Xato: {ex.Message}"); } class Person { private int age; public string Name { get; set; } = ""; public int Age { get => age; set { if (value < 18) throw new Exception("18 yoshga to'lmagan shaxslarni ro'yxatdan o'tkazish taqiqlanadi"); else age = value; } } } Ammo ba'zida o'zingizning istisno sinflaringizdan foydalanish qulayroqdir. Misol uchun, ba'zi holatlarda biz faqat Person sinfiga tegishli istisnolarni ma'lum bir tarzda hal qilishni xohlaymiz. Ushbu maqsadlar uchun biz maxsus PersonException sinfini yaratishimiz mumkin: class PersonException : Exception { public PersonException(string message) : base(message) { } } try{Person person = new Person { Name = "Tom", Age = 17 };} catch (PersonException ex) { Console.WriteLine($"Xato: {ex.Message}"); } class Person { private int age; public string Name { get; set; } = ""; public int Age { get => age; set { if (value < 18) throw new PersonException("18 yoshga to'lmagan shaxslarni ro'yxatdan o'tkazish taqiqlanadi "); else age = value; } } } try{Person person = new Person { Name = "Tom", Age = 17 };} catch (PersonException ex) { Console.WriteLine($"Xato: {ex.Message}"); } class Person { private int age; public string Name { get; set; } = ""; public int Age { get => age; set { if (value < 18) throw new PersonException("18 yoshga to'lmagan shaxslarni ro'yxatdan o'tkazish taqiqlanadi "); else age = value; } } }
Adabiyotlar
1. https://docs.microsoft.com/ru-ru/dotnet/csharp/fundamentals/object-oriented/polymorphism -Polimorfizm haqida ma’lumot
2. https://metanit.com/sharp/tutorial/3.19.php -Virtual usullar va xususiyatlarga doir ma’lumotlar.
Do'stlaringiz bilan baham: |