### "Конспект лекции "Исключения" ### 1) Деление на ноль без обработки исключения ``` int x = 5; int y = x / 0; Console.WriteLine($"Результат: {y}"); Console.WriteLine("Конец программы"); Console.Read(); ``` ``` Unhandled exception. System.DivideByZeroException: Attempted to divide by zero. at Program.
$(String[] args) in /home/kei/RiderProjects/tryCatch/Program.cs:line 2 Process finished with exit code 134. ``` ### 2) Деление на ноль с обработкой исключения ``` try { int x = 5; int y = x / 0; Console.WriteLine($"Результат: {y}"); } catch { Console.WriteLine("Возникло исключение!"); } finally { Console.WriteLine("Блок finally"); } Console.WriteLine("Конец программы"); Console.Read(); ``` ``` Возникло исключение! Блок finally Конец программы ``` ### 3) Обработка исключения с фильтром ``` int x = 1; int y = 0; try { int result = x / y; } catch (DivideByZeroException) when (y == 0 && x == 0) { Console.WriteLine("y не должен быть равен 0"); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } ``` ``` Attempted to divide by zero. ``` ### 4) Обработка исключения с использованием Exception ``` try { int x = 5; int y = x / 0; Console.WriteLine($"Результат: {y}"); } catch (Exception ex) { Console.WriteLine($"Исключение: {ex.Message}"); Console.WriteLine($"Метод: {ex.TargetSite}"); Console.WriteLine($"Трассировка стека: {ex.StackTrace}"); } Console.Read(); ``` ``` Исключение: Attempted to divide by zero. Метод: Void
$(System.String[]) Трассировка стека: at Program.
$(String[] args) in C:\Users\Admin\labs\oap_labs\oap_labs\Program.cs:line 4 ``` ### 5) Cоздание класса исключения ``` class PersonException : Exception { public int Value { get; } public PersonException(string message, int val) : base(message) { Value = val; } } class Person { public string Name { get; set; } private int age; public int Age { get { return age; } set { if (value < 18) throw new PersonException("Лицам до 18 регистрация запрещена", value); else age = value; } } } try { Person p = new Person { Name = "Tom", Age = 13 }; } catch (PersonException ex) { Console.WriteLine($"Ошибка: {ex.Message}"); Console.WriteLine($"Некорректное значение: {ex.Value}"); } Console.Read(); ``` ``` Ошибка: Лицам до 18 регистрация запрещена Некорректное значение: 13 ``` ### 6) Поиск блока catch в стеке вызовов ``` try { TestClass.Method1(); } catch (DivideByZeroException ex) { Console.WriteLine($"Catch в Main: {ex.Message}"); } finally { Console.WriteLine("Блок finally в Main"); } Console.WriteLine("Конец метода Main"); Console.Read(); class TestClass { public static void Method1() { try { Method2(); } catch (IndexOutOfRangeException ex) { Console.WriteLine($"Catch в Method1: {ex.Message}"); } finally { Console.WriteLine("Блок finally в Method1"); } Console.WriteLine("Конец метода Method1"); } static void Method2() { try { int x = 8; int y = x / 0; } finally { Console.WriteLine("Блок finally в Method2"); } Console.WriteLine("Конец метода Method2"); } } ``` ``` Блок finally в Method2 Блок finally в Method1 Catch в Main: Attempted to divide by zero. Блок finally в Main Конец метода Main ``` ### 7) Генерация исключения с помощью throw ``` try { Console.Write("Введите строку: "); string message = Console.ReadLine(); if (message.Length > 6) { throw new Exception("Длина строки больше 6 символов"); } } catch (Exception e) { Console.WriteLine($"Ошибка: {e.Message}"); } Console.Read(); ``` ``` Введите строку: HelloWorld Ошибка: Длина строки больше 6 символов ``` ### 8) Использование оператора условного null ``` class User { public Phone Phone { get; set; } } class Phone { public Company Company { get; set; } } class Company { public string Name { get; set; } } User user = new User(); string companyName = user?.Phone?.Company?.Name ?? "не установлено"; Console.WriteLine(companyName); ``` ``` не установлено ```