Обробка винятків

try-catch

try { 

catch (Exception ex) { 

     Console.WriteLine(ex.Message); 

}

Після try-catch 

finally { 

}

Згенерувати виняток

throw new Exception("Довжина більше 10 символів");

throw new ArgumentException("Argh!");

throw new NotImplementedException();

Обробка різних винятків

int x1, x2, d, sum = 0;

for (int i = 10; i < 30; i++)

{

     try

     {

          string a = File.ReadAllText(i + ".txt");

          string[] b = a.Split('\n');

          x1 = Convert.ToInt32(b[0]);

          x2 = Convert.ToInt32(b[1]);

          d = checked(x1 * x2);

          sum += d;

          Console.WriteLine(i + ". d = " + d);

     }

     catch (FileNotFoundException ex)

     {

          File.AppendAllText("no_file.txt", i + ".txt");

     }

     catch (FormatException ex)

     {

          File.AppendAllText("bad_data.txt", i + ".txt");

     }

     catch (OverflowException ex)

     {

          File.AppendAllText("overflow.txt", i + ".txt");

     }

}