문제

Following the example in book and got the following slightly modified code:

 class OutOfHoneyException : Exception
 {
    public OutOfHoneyException(string message) :base(message){}
 }

    class HoneyDeliverSystem
    {
        public void FeedHoneyToEggs()
        {
            if (true)
            {
                throw new OutOfHoneyException("This hive is Out Of Honey");
            }
        }
    }

.....................................

 HoneyDeliverSystem delivery = new HoneyDeliverSystem();

      try
        {
            delivery.FeedHoneyToEggs();
        }
        catch (OutOfHoneyException ex)
        {

            Console.WriteLine(ex.Message);
        }

What I understand when ever a specific exception is thrown by us in specific condition, the corresponding catch block handles that.

But please help me with a better example, maybe .NET exception's implementation will be really helpful.

And why are we passing the message to the base Exception class? Is it only for printing purpose?

There is a OOPS concept for child class calling base class constructor. Could you please name it and how it is related to custom exceptions example?

도움이 되었습니까?

해결책

The best thing to do is put your new exception in it's own file and make it public. The base Exception class has 4 constructors and in most cases it'd be useful to implement at least the first 3:

public class OutOfHoneyException : Exception
{
    public OutOfHoneyException()
        : base()
    {
    }

    public OutOfHoneyException(string message)
        : base(message)
    {
    }

    public OutOfHoneyException(string message, Exception innerException)
        : base(message, innerException)
    {
    }

    public OutOfHoneyException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }
}

You inherit from the Exception class, because it has all the basic exception implementation/behaviour that is expected when handling an custom exception.

You need to implement all 4 constructors to make your new custom exception feel even more like a typical .NET exception.

Two things to note when learning things about exceptions, is firstly that exceptions should be thrown only for exceptional behaviour and secondly that exceptions shouldn't be used to control program flow. These 2 rules kind of fit together.

For example if you were querying a stock control system to see how many cans of beans were in stock, then a result of 0 would be a common answer and although it wouldn't be a desirable answer for the customer, it's not exceptional. If you queried the stock system for cans of beans and the database server wasn't available, that's exceptional behaviour outside of the common result you were expecting.

다른 팁

You are not very far away from common practice. I would have done it like this:

class OutOfHoneyException : Exception {
  public OutOfHoneyException() : base("This hive is Out Of Honey"){}
}

class HoneyDeliverSystem {
  public void FeedHoneyToEggs() {
    throw new OutOfHoneyException();
  }
}

I mean, there in no reason to have a different message for an OutOfHoneyException, is there?

When you pass the message to the base class(Exception), the base class will set Message property of your exception and do all helpful stuff like keeping StackTrace.

So when you catch your custom exception (OutOfHoneyException), the message field will be set by your base Exception class. Checkout the following code from implementation:

/// <summary>
/// Initializes a new instance of the <see cref="T:System.Exception"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error. </param>
public Exception(string message)
{
  base..ctor();
  this.Init();
  this._message = message;
}

/// <summary>
/// Initializes a new instance of the <see cref="T:System.Exception"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception. </param><param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. </param>
public Exception(string message, Exception innerException)
{
  base..ctor();
  this.Init();
  this._message = message;
  this._innerException = innerException;
}

Rather than write an answer telling you how to create an exception I am going to try and answer your specific questions.

And why are we passing the message to the base Exception class? Is it only for printing purpose?

More or less. The message is to add context to the exception. There could be several reasons why the OutOfHoneyException is thrown - the bees are asleep, they are on holiday, an anteater ran out of ants and decided he liked bees instead, etc.

There is a OOPS concept for child class calling base class constructor. Could you please name it and how it is related to custom exceptions example?

No matter which constructor you use on the derived class the default constructor will always be called on the base class unless you specify a different one (which is what is happening here). This is basic constructor overloading which gives you a reasonable amount of flexibility when creating derived classes (also note that there is constructor chaining).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top