Create a C program named BookExceptionDemo for the Peterman
Create a C# program named BookExceptionDemo for the Peterman Publishing Company. Create a BookException class that is instantiated when a Book’s price exceeds 10 cents per page and whose constructor requires three arguments for title, price, and number of pages. Create an error message that is passed to the Exception class constructor for the Message property when Book does not meet the price-to-pages 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-somewhere the ratio is acceptable, and others where it is not. Catch any thrown exceptions, and display the BookException Message.
.
Solution
The Code For Above Problem is given below.
Note: Here I have created one instance of book class for demo. You can create any number of objects in similar fashion. :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class BookExceptionDemo
{
static void Main(string[] args)
{
Book newBook = null;
Book newBook1 = null;
Book newBook2 = null;
Book newBook3= null;
try
{
newBook = new Book();
newBook.price = 12.99;
newBook.title = \"Random book\";
newBook.author = \"RR Martin\";
newBook.numberOfPages = 25;
ValidateBookRatio(newBook);
}
catch (BookException ex)
{
Console.WriteLine(ex.Message);
}
}
private static void ValidateBookRatio(Book bk)
{
double temp=0;
temp=(bk.price*100)/bk.numberOfPages;
if (temp>10.0)
throw new BookException(bk.title,bk.price,bk.numberOfPages);
}
}
class Book
{
public string title { get; set; }
public string author { get; set; }
public double price { get; set; }
public int numberOfPages { get; set; }
}
[Serializable]
class BookException : Exception
{
public BookException()
{
}
public BookException(string title,double price,int numberOfPages)
: base(String.Format(\"For {0}, ratio is invalid....Price is $ {1} for {2}pages\", title,price,numberOfPages))
{
}
}
}
