C# Винятки (більше)


finally { 

}

Звільняє пам'ять, яка могла бути виділеною в try
Завжди спрацьовує, може бути і без catch



Генерація винятки різних типів

throw new Exception("Довжина більше 10 символів");
throw new ArgumentException("Arg!");
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");
     }
}

 


Основні класи

1. ArithmeticException
     DivideByZeroException
     NotFiniteNumberException
     OverflowException int = 1111111111111111111111111111111111111111  
     FormatException ToInt32() - пуста, чи не цифра
2. ArgumentException
     ArgumentNullException
     ArgumentOutOfRangeException
3. ArrayTypeMismatchException
4. IndexOutOfRangeException
5. InvalidCastException
6. InvalidOperationException
7. IOException
     DirectoryNotFoundException
     EndOfStreamException
     FileNotFoundException
     FileLoadException
     PathTooLongException
8. NullReferenceException
9. OutOfMemoryException
10. StackOverflowException



Свій клас

class PersonException : Exception  // ArithmeticException...
{
  public PersonException(string message) : base(message)
  {
  }
}