using System;
namespace ExceptionDemo
{
class Program
{
// Метод деления — генерирует исключение ArithmeticException
static double Divide(int a, int b)
{
if (b == 0)
throw new DivideByZeroException("Попытка деления на ноль!");
return (double)a / b;
}
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
int x = 0, y = 0;
// ========== СТАНДАРТНОЕ ИСКЛЮЧЕНИЕ №1: FormatException ==========
try
{
Console.Write("Введите первое число: ");
string buf = Console.ReadLine();
x = int.Parse(buf); // ← если буквы, бросит FormatException
}
catch (FormatException e)
{
Console.WriteLine("\n=== FormatException ===");
Console.WriteLine("Message: " + e.Message);
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("TargetSite: " + e.TargetSite);
return;
}
try
{
Console.Write("Введите второе число: ");
string buf = Console.ReadLine();
y = int.Parse(buf);
}
catch (FormatException e)
{
Console.WriteLine("\n=== FormatException ===");
Console.WriteLine("Message: " + e.Message);
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("TargetSite: " + e.TargetSite);
return;
}
// ========== СТАНДАРТНОЕ ИСКЛЮЧЕНИЕ №2: DivideByZeroException ==========
try
{
double result = Divide(x, y);
Console.WriteLine("\nРезультат: " + result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("\n=== DivideByZeroException ===");
Console.WriteLine("Message: " + e.Message);
Console.WriteLine("Source: " + e.Source);
Console.WriteLine("TargetSite: " + e.TargetSite);
Console.WriteLine("StackTrace: " + e.StackTrace);
}
catch (Exception e)
{
Console.WriteLine("\n=== Общее исключение ===");
Console.WriteLine("Message: " + e.Message);
}
Console.WriteLine("\nДля выхода нажмите Enter...");
Console.ReadLine();
}
}
}