954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to throw an exception

hi
im trying to write a program that will create a class to store info on books (title, author, number of pages and price) and that will trow a custom exception when the price entered for a book is higher than 10 cents per page. I got the class working but i cant figure out how to throw the exception any help would be appreciated.

alex9292
Newbie Poster
14 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 
hi im trying to write a program that will create a class to store info on books (title, author, number of pages and price) and that will trow a custom exception when the price entered for a book is higher than 10 cents per page. I got the class working but i cant figure out how to throw the exception any help would be appreciated.

Do you really want to throw an exception? Or just test the price and throw up a messagebox alerting them that the price is not acceptable? And/or allow them to to confirm the price is what they entered?

Assuming you really don't want to throw an exception ... you would want to a test at the top of your method with an if/else (before you commit he data) ... and if its above your 10 cents a page, throw up a messagebox and let the user respond. If they confirm its the right price, commit the data ... if the user confirms its not the right price, then exit the method without committing the data.

I would have the method return a boolean (true/false) response to the calling code, so that code knows whether to clear the data that they just tried to commit ... or just leave it for modification if it wasn't committed.

If you gave us some code to visualize, we could give a better example.

Zinderin
Junior Poster in Training
76 posts since Jun 2010
Reputation Points: 22
Solved Threads: 8
 

i need to throw an exception its for a school project.

this is what i have so far

using System;
public class BookExceptions
{
    public static void Main()
    {
        string InputPages ;
        string InputPrice ;

        Book book1 = new Book();
        Console.Write("Please enter the book's title : ");
        book1.Title = Console.ReadLine();

        Console.Write("Please enter the book's author : ");
        book1.Author = Console.ReadLine();

        Console.Write("Please enter the number of pages in the book : ");
        InputPages = Console.ReadLine();
        book1.Pages = Convert.ToInt32(InputPages);
        book1.MaxPrice = book1.Pages * 0.10;
        
        while ()
        {
            try
            {
                Console.Write("Please enter the book's price :  ");
                InputPrice = Console.ReadLine();
                book1.Price = Convert.ToDouble(InputPrice);

            }
            catch ( BookException be )
            {
                Console.Write ( be.Message);
                Console.WriteLine("For {0} the maximum price allowed for a {1} page is {2}$", book1.Title, book1.Pages, book1.Pages * 0.10);
            }
        }
        Console.WriteLine("The title of Book 1 is {0} by {1} it contains {2} pages and is priced at {3}$.", book1.Title, book1.Author, book1.Pages, book1.Price);
        Console.ReadLine();

        
    }






    public class Book
    {
        public string Title { get; set; }
        public string Author { get; set; }
        public int Pages { get; set; }
        public double Price { get; set; }
        public double MaxPrice { get; set; }

    }

    public class BookException : Exception
    {

        private static string msg = "The ratio is invalid.";
        public BookException() : base(msg) { }
        
        
    }
    
}
alex9292
Newbie Poster
14 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

So are you looking for:

catch ( BookException be )
{
    Console.Write ( be.Message);
    throw new System.InvalidOperationException("For {0} the maximum price allowed for a {1} page is {2}$", book1.Title, book1.Pages, book1.Pages * 0.10);
}


???? (BTW, I didn't test that code)

Zinderin
Junior Poster in Training
76 posts since Jun 2010
Reputation Points: 22
Solved Threads: 8
 

i tried your code and i got error cs1729 System.InvalidOperationException does not contain a constructor that takes 4 arguments

alex9292
Newbie Poster
14 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

If you really need to propagate the exception to global scope, you can add a String.Format:

throw new System.InvalidOperationException(
				String.Format(
				"For {0} the maximum price allowed for a {1} page is {2}$"
				, book1.Title, book1.Pages, book1.Pages * 0.10)
				);

.. but, your basic handler might be enough. The System exception re-throw is only if the problem is so bad you have nothing left to do but crash out of your whole program.

wisaacs
Light Poster
46 posts since Jun 2010
Reputation Points: 8
Solved Threads: 5
 

i tried your code it compiles ok but my problem is still that it doesnt throw the exception it executes ok but it doesnt see that the price is wrong. It has to re prompt for a price until the price is acceptable (<= 0.10$ per page).

alex9292
Newbie Poster
14 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

well, from wat i have seen, you probably are not checking the condition as to what shud it prompt it it exceeds 10 cents...

arunkumars
Junior Poster
186 posts since Jul 2009
Reputation Points: 26
Solved Threads: 22
 

u can go abt in a simpler way rather than throwing an exception,
if (book1.MaxPrice > 10 cents) // i dnt knw the currency stuff here
{
MessageBox.Show(Your message..);
}

OR

If there is a Business logic layer that u r using, u can set your property saying it cannot exceed 10 cents.

arunkumars
Junior Poster
186 posts since Jul 2009
Reputation Points: 26
Solved Threads: 22
 
// plain old unprotected variable called 'price'
    class A
    {
        public double price =0;
    } // end, class A

// this class works just the same, but uses a property instead
    class B
    {
        private double _price =0;
        public double price
        {
            get { return _price; }
            set
            {
                if (value < 0 || value > 100.00)
                    throw new Exception("bad price");
                _price = value;
            }
        }
    } // end, class B

    class Program
    {
        public static void Main(string[] args)
        {
            A a = new A();
            a.price = -99999999.00234;   // you can set this to anything.. 
            Console.WriteLine("{0} for a book?  No Problem!",a.price);
            B b = new B();
            b.price = 99999999.00234;   // try a property!
            // KABOOM
            Console.WriteLine("happy ending"); // we never get here
        }
    } // end Program


Now, rather than blowing up, you might want to catch the exception...

class B
    {
        private double _price = 0;
        public double price
        {
            get { return _price; }
            set
            {
                if (value < 0 || value > 100.00)
                    throw new Exception(
                        string.Format(
                        "What!  {0} (?) Bad price. What were you thinking?"
                        , value
                        ));
                _price = value;
            }
        }
    } // end, class B

    class Program
    {
        public static void Main(string[] args)
        {
            B b = new B();
            try // no KABOOM, KABOOM bad
            {
                b.price = 99999999.00234;   // now try it..
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            // normal happy continuation
            b.price = 99.50;
            Console.WriteLine("happy ending");
        }
    } // end Program
wisaacs
Light Poster
46 posts since Jun 2010
Reputation Points: 8
Solved Threads: 5
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: