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.