Книга: C# 2008 Programmer

Using Exception Objects

Using Exception Objects

Instead of using the default description for each exception class you are throwing, you can customize the description of the exception by creating an instance of the exception and then setting the Message property. You can also specify the HelpLink property to point to a URL where developers can find more information about the exception. For example, you can create a new instance of the ArithmeticException class using the following code:

if (num1 == 0) {
 ArithmeticException ex =
  new ArithmeticException("Value of num1 cannot be 0.") {
   HelpLink = "http://www.learn2develop.net"
  };
 throw ex;
}

Here's how you can modify the previous program by customizing the various existing exception classes:

class Program {
 static void Main(string[] args) {
  int num1, num2;
  try {
   Console.Write("Please enter the first number:");
   num1 = int.Parse(Console.ReadLine());
   Console.Write("Please enter the second number:");
   num2 = int.Parse(Console.ReadLine());
   Program myApp = new Program();
   Console.WriteLine("The result of {0}/{1} is {2}", num1, num2,
    myApp.PerformDivision(num1, num2));
  } catch (DivideByZeroException ex) {
   Console.WriteLine(ex.Message);
  } catch (ArithmeticException ex) {
   Console.WriteLine(ex.Message);
  } catch (FormatException ex) {
   Console.WriteLine(ex.Message);
  } catch (Exception ex) {
   Console.WriteLine(ex.Message);
  }
  Console.ReadLine();
 }
 private int PerformDivision(int num1, int num2) {
  if (num1 == 0) {
   ArithmeticException ex =
    new ArithmeticException("Value of num1 cannot be 0.") {
     HelpLink = "http://www.learn2develop.net"
    };
   throw ex;
  }
  if (num2 == 0) {
   DivideByZeroException ex =
    new DivideByZeroException("Value of num2 cannot be 0.") {
     HelpLink = "http://www.learn2develop.net"
    };
   throw ex;
  }
  return num1 / num2;
 }
}

Here's the output when different values are entered for num1 and num2:

Please enter the first number:0
Please enter the second number:5
Value of num1 cannot be 0.
Please enter the first number:5
Please enter the second number:0
Value of num2 cannot be 0.

Оглавление книги


Генерация: 0.035. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз