TimTheEnchanter
TimTheEnchanter

Reputation: 63

Inheritance and Exception Handling

I am trying to complete a homework assignment however I am not sure what to do next. I have been struggling with Inheritance and Exception Handling...this problem combines the two. Could you please give me a shove in the right direction?

Here is the question: Create a program named BookExceptionDemo for the Peterman Publishing Company. The company has decided that no published book should cost more than 10 cents per page. Create a BookException class whose constructor requires three arguments: a string Book title, a double price, and an int number of pages. Create an error message that is passed to the Exception class constructor for the Message property when a book does not meet the price-to-page ratio. For example, an error message might be:

For Goodnight Moon, ratio is invalid. ...Price is $12.99 for 25 pages.

Create a Book class that contains fields for title, author, price, and number of pages. Include properties for each field. throw a BookException if a client program tries to construct a Book object for which the price is more than 10 cents per page. Create a program that creates at least four Book objects - some where the ratio is acceptable and others where it is not. Catch any thrown exceptions and display the BookException Message.

Here is what I have so far:

namespace BookExceptionDemo
{
    class BookException : Exception
    {
        public BookException(string title, double price, int numberPages)
             : base("For " + title + ", ratio is invalid. \nPrice is $" + price + " for " + numberPages + " pages.") //p.470
        {
        }
    }

    class Book
    {
        public Book(string title, double price, int numberPages)  //he said this should check to see if the ratio is correct, if not, then throw exception.
        { 
        }

        public string Title { get; private set; }

        public double Price { get; private set; }

        public int NumberPages { get; private set; }
    }

    // my teacher put this here
    // but at the end of class he said the contents should be moved somewhere else?
    // Does it go in the BookException constructor? 
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                throw (new BookException("Goodnight Moon", 12.99, 25));
            }
            catch (BookException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.Read();
       }
    }
}

EDIT My school switched programming languages this semester, so I came into this intermediate C# course with no prior knowledge of the language. I understood most things up until the past few class sessions. I was getting frustrated in my confusion and was feeling disheartened, but now I can honestly say that I am excited to have a better understanding of these concepts. Programming is really fun and I really appreciate people like you who are willing to help others. Thank you all for the time and effort you have given in assisting me.

Here is what I believe to be the correct answer to the question I posted.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BookExceptionDemo
{
    class BookException : Exception
    {
        public BookException(string title, double price, int numberPages)
            : base("For " + title + ", ratio is invalid. \nPrice is $" + price + " for " + numberPages + " pages.")
        {

        }
    }

    class Book
    {
        public Book(string title, string author, double price, int numberPages)
        {
            if ((price / numberPages) > .1)
            {
                throw new BookException(title, price, numberPages);
            }
        }

        private string title;
        private string author;
        private double price;
        private int numberPages;


        public string Title
        {
            get
            {
                return title;
            }
            set 
            {
                title = value;
            }
        }

        public string Author
        {
            get
            {
                return author;
            }
            set
            {
                author = value;
            }
        }

        public double Price
        {
            get
            {
                return price;
            }
            set
            {
                price = value;
            }
        }

        public int NumberPages
        {
            get
            {
                return numberPages;
            }
            set
            {
                numberPages = value;
            }
        }

    }

    class Program 
    {
        static void Main(string[] args)
        {
            try
            {
                Book junglebook = new Book("Jungle Book","Kipling", 25.99, 50);   //should throw exception
            }
            catch (BookException ex)
            {
            Console.WriteLine(ex.Message);
            }

            try
            {
                Book hobbit = new Book("The Hobbit","Tolkien", 2.99, 30);   //should NOT throw exception
            }
            catch (BookException ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                Book book1984 = new Book("1984","Orwell", 31.32, 15);   //should throw exception
            }
            catch (BookException ex)
            {
                Console.WriteLine(ex.Message);
            }

            try
            {
                Book guidetonetworks = new Book("Guide to Networks","Somebody", 17.56, 500);   //should NOT throw exception
            }
            catch (BookException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Read();
        }
    }
}

Upvotes: 3

Views: 5146

Answers (2)

pm100
pm100

Reputation: 50190

public Book(string title, double price, int numberPages)
{
   if(price / numberPages > 0.1)
      throw new BookException(title, price, numberPages);
}

Upvotes: 0

BradleyDotNET
BradleyDotNET

Reputation: 61349

The concept of exceptions is that something really bad has happened. So bad that you are interrupting the control flow of the program.

In this case, you need to throw as (effectively) a validation step when creating a book. The check needs to happen on book creation, so we put it in the constructor:

public Book(string title, double price, int numberPages)
{ 
    bool goodPrice = true; //Actual condition left as an exercise
    if (!goodPrice) //No good, bail!
        throw new BookException(title, price, numberPages);
}

The calling code will need to wrap any invocations of Books constructor in a try/catch to handle this. Be aware that a thrown exception breaks normal control flow, the catch block is immediately entered and control is not returned to the try block.

The Program class and indeed all these classes, typically reside in their own files, which is possibly what your instructor was alluding to by saying it would normally be somewhere else.

Regardless, you already know how to invoke a constructor (through instantiation, you did it for the exception!). Now you just need to create a few Book objects (some with invalid parameters). With the code given, the Main method makes sense for this.

A sample call would look like:

try
{
   Book introToC = new Book("C# is Awesome!", 10.00, 100);
}
catch (BookException ex) //Specify what we are catching!
{
   //Do something, in your case print. (Left as exercise).
}

Update

To your question about why we use try/catch. First, I suggest you ask your instructor, as he will explain it better than I can :).

However, try to imagine your objects as actual objects and it makes a bit more sense. Suppose I had a "SuperBigButton" class with a "Click" method. In real terms, its a super big button I can push.

Suppose I then push that button, but I forgot to turn it on (I'm not terribly bright in this example). Now, the thing attached to the button could just print out an error message, or even do nothing, but the point is I don't know anything is wrong.

It is better if it punches me in the face, saying "You didn't turn it on!". This is much more useful to me (the calling code). Certainly there are patterns where bool return values are used instead of exceptions (the TryParse family of functions come to mind) but this is why we use exceptions. We need to be able to "error out" and tell the calling code something is broken.

Exceptions also have the advantage of interrupting the control flow, so anything in the calling code that depended on the given call succeeding will not run (they are skipped as control moves to the catch block).

Upvotes: 1

Related Questions