Книга: C# 2008 Programmer

Creating Custom Exceptions

Creating Custom Exceptions

The .NET class libraries provide a list of exceptions that should be sufficient for most of your uses, but there may be times when you need to create your own custom exception class. You can do so by deriving from the Exception class. The following is an example of a custom class named AllNumbersZeroException:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AllNumbersZeroException : Exception {
 public AllNumbersZeroException() {}
 public AllNumbersZeroException(string message) : base(message) {}
 public AllNumbersZeroException(string message, Exception inner) : base(message, inner) {}
}

To create your own custom exception class, you need to inherit from the Exception base class and implement the three overloaded constructors for it.

The AllNumbersZeroException class contains three overloaded constructors that initialize the constructor in the base class. To see how you can use this custom exception class, let's take another look at the program you have been using all along:

static void Main(string[] args) {
 int num1, num2, result;
 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 (AllNumbersZeroException ex) {
  Console.WriteLine(ex.Message);
 } 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 && num2 == 0) {
  AllNumbersZeroException ex =
   new AllNumbersZeroException("Both numbers cannot be 0.") {
    HelpLink = "http://www.learn2develop.net"
   };
  throw ex;
 }
 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;
}

This program shows that if both num1 and num2 are zero, the AllNumbersException exception is raised with the custom message set.

Here's the output when 0 is entered for both num1 and num2:

Please enter the first number:0
Please enter the second number:0
Both numbers cannot be 0.

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

Оглавление статьи/книги

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