继承和异常处理

时间:2014-11-25 00:21:00

标签: c# inheritance exception-handling

我正在尝试完成家庭作业,但我不知道下一步该做什么。我一直在努力继承和异常处理...这个问题结合了两者。 能否请你朝正确的方向推?

以下是问题: 为Peterman Publishing Company创建一个名为BookExceptionDemo的程序。该公司已决定,任何出版的图书每页的成本不应超过10美分。创建一个BookException类,其构造函数需要三个参数:字符串书名,双倍价格和int页数。当书籍不符合价格与页面比率时,创建一个错误消息,该消息将传递给Message属性的Exception类构造函数。例如,错误消息可能是:

对于晚安月亮,比例无效。 ... 25页的价格是12.99美元。

创建一个Book类,其中包含标题,作者,价格和页数的字段。包含每个字段的属性。如果客户端程序试图构造一个价格超过每页10美分的Book对象,则抛出BookException。创建一个程序,创建至少四个Book对象 - 其中一些比例是可接受的,另一些不是。捕获任何抛出的异常并显示BookException消息。

这是我到目前为止所做的:

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();
       }
    }
}

修改 我的学校这个学期改变了编程语言,所以我进入了这个中级C#课程,没有语言的先验知识。直到过去的几节课,我才了解大多数事情。我对自己的困惑感到沮丧并且感到沮丧,但现在我可以诚实地说,我很高兴能够更好地理解这些概念。编程非常有趣,我非常感谢像你这样愿意帮助他人的人。感谢大家为我提供的时间和精力。

我认为这是我发布的问题的正确答案。

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();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

例外的概念是真的坏事发生了。 太差了​​,你正在打断程序的控制流程。

在这种情况下,您需要在创建图书时(有效地)抛出验证步骤。检查需要在创建图书时进行,因此我们将其放在构造函数中:

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);
}

调用代码需要在Book中包装try/catch构造函数的任何调用来处理这个问题。请注意抛出的异常会破坏正常的控制流,会立即输入catch块,并且不会将控制权返回给try块。

Program类以及所有这些类通常都存在于他们自己的文件中,这可能是教师提到的,通常说它通常在其他地方。

无论如何,你已经知道如何调用构造函数(通过实例化,你为异常做了!)。现在您只需创建一些Book个对象(其中一些具有无效参数)。使用代码,Main方法对此有意义。

示例调用如下:

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).
}

<强>更新

关于我们使用try/catch的原因的问题。首先,我建议你问你的导师,因为他会比我能更好地解释:)。

但是,尝试将对象想象为实际对象并且它更有意义。假设我有一个带有“Click”方法的“SuperBigButton”类。实际上,它是我可以推动的一个超级大按钮。

假设我然后按下那个按钮,但我忘了打开它(在这个例子中我并不是非常明亮)。现在,附在按钮上的东西可以打印出错误信息,甚至什么都不做,但重点是我不知道有什么不对

如果它击打我的脸,说“你没有打开它!”,这样会更好。这对我来说是非常有用的(调用代码)。当然有些模式使用bool返回值而不是异常(我会想到TryParse函数族)但这就是我们使用异常的原因。我们需要能够“出错”并告诉调用代码有问题。

异常还具有中断控制流的优点,因此依赖于给定调用成功的调用代码中的任何内容都不会运行(当控件移动到catch块时,它们会被跳过)。