Writing own exception class

LittleRedHat
LittleRedHat used Ask the Experts™
on
I am using the following method and test method, which works fine.  However, I understand that rather than using this, I could write my own exception class and then "try/catch" if the maximum number of toppings are exceeded, but am not having much success with my DIY attempts to do this.

Help would be appreciated.  

WTA.

LRH

// METHOD TO ADD TOPPINGS          

     public void addTopping (String newType, float newWeight, float newCost){
          if (numToppings == MAXTOPPINGS)
               {
               System.out.println(" Only 6 toppings allowed. The last topping will not be added");
               return;
               }

          toppingList[numToppings] = new Topping(newType, newWeight, newCost);
          numToppings++ ;
     }

// TEST ADDING TOPPINGS METHOD
         
          System.out.println ("\n Add Tomato Paste");
          Pizza1.addTopping("tomatoPaste", 15F, 1F);
          System.out.println ("\n Add Cheese");
          Pizza1.addTopping("cheese", 25F, 2.5F);
          ... etc till the allowed 6 exceeded
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,
option 1:

public void addTopping (String newType, float newWeight, float newCost){
         if (numToppings == MAXTOPPINGS)
              throw new RuntimeException("Only 6 toppings allowed. The last topping will not be added");
option 2 (less recommended):

class TooMuchToppingException extends Exception /* or RuntimeException */ {
 public TooMuchToppingException () {
    super("Too much topping was added");
 }

public TooMuchToppingException (int toppingNum) {
    super("Too much topping was added topping=" + toppingNum);
 }

 public TooMuchToppingException (String msg) {
    super(msg);
 }
}

and then:
if (numToppings == MAXTOPPINGS)
             throw new TooMuchToppingException(6);

-gkern
Commented:
if you want to create an exception class of your own, basically u would do

public class MyException extends Exception{
 public MyException(){
 super();
 // anything else u want to add
}

 public MyException(String e){
 super(e);
 // anything else u want to add
}

and then in your class u would say

if (numToppings == MAXTOPPINGS)
              {
throw new MyException("Only 6 toppings allowed. The last topping will not be added");
              }

Hope this is what u wanted
vemul
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

notic that if u extends Exception the user of the method will be force to use try and catch !

-gkern
last thing, if u extends Exception  u have to change the method signature to:

public void addTopping (String newType, float newWeight, float newCost) throws TooMuchToppingException

-gkern

Author

Commented:
Wow!  Many thanks to you both for the speedy replies.

I'll get working on your advice right now and come back later to let you know how I've got on.

Regards

LRH
glad i could help :)
-gkern

Commented:
This is not a good candidate for a RuntimeException (descendant)

RuntimeException should be used for Exceptions only where the program has no means of correcting this error. Prompting the user to enter a smaller number of toppings would be such a remedy. It might be more convient to use RuntimeException since you need not to include all these catch/throws but it looks like lazy programming to me.

Beside this, I doubt that you should go with that "programming by exception" idea. On the plus side your code is more readable, but the downside might be a degraded perfomance and a large number of exceptions to be defined that are used only in very few parts of the program.
Distinguished Expert 2018

Commented:
 You might be also able to find some hints by reading the Java Exception tutorial:

http://java.sun.com/docs/books/tutorial/essential/exceptions/

Commented:
Another point to add.. using a try /catch block and throwing exceptions is considered to be very expensive and should be used as minimal as possible

vemul
this is correct, usually exceptions/try/catch is consider to be bad programming, BUT a good programmer sould be able to use those technics and to create his own Exceptions when needed

-gkern

Commented:
>>> usually exceptions/try/catch is consider to be bad programming

really?

Commented:
gkern,
 I am not at all suggesting that creating and using exceptions is bad. All I am saying is that it should be used minimal AND only when REQUIRED.

I am sure u would agree that this condition
if (numToppings == MAXTOPPINGS)

would not qualify itself to throw an exception. it is a valid case and the user should handle it in such a way that he should either print out or pop up a dialog saying it exceeded blah blah.. and accordingly do something

vemul

Commented:
... double divide(double divider) {
if (divider==0.0) throw new ArithmeticException()
...
}

is a clear candidate for a RuntimeException

A good hint whether to throw an exception or to handle it programmatically might be:

It's a business rule, hence it isn't an exception

Author

Commented:
Apologies that I haven't got back sooner.  I was called away and haven't yet had chance to try your suggestions. :-( I will report back as soon as I get under way.  

With thanks to everyone for all the extra information.  It's been helpful reading your views.

Best regards.

LRH  
Mick BarryJava Developer
Top Expert 2010

Commented:
> I am sure u would agree that this condition
> if (numToppings == MAXTOPPINGS)
> would not qualify itself to throw an exception

No I wouldn't agree. This is a perfect case fopr throwing an exception.
How else would you inform the calling method that it failed to add a topping, and why?

Commented:
objects,
now if we keep throwing exceptions for each possible user case, then I feel it would get real ugly.

For example, let's consider a scenario where the user enters nothing(null). So in order to notify the user, what would be better, an exception or some way of telling the user (pop up or something in those lines)??

Same thing, if users enters something not within a valid range, I feel you should notify the user instead of throwing an exception (unless you are doing something in the exception handling)

Once again, my whole point was in conveying that throwing exceptions should be done as minimal as possible but wasn't suggesting of eliminating them.

There is a very thin line that differentiates how to handle these and my view varies from yours. :-)

vemul
Mick BarryJava Developer
Top Expert 2010

Commented:
If the user enters invalid data, then that is a RuntimeException.
But you still haven't answered my question, how do you propose to inform the calling class that adding the topping failed?

Commented:
>> But you still haven't answered my question, how do you propose to inform the calling class that adding the topping failed?

sorry I previously saw your "calling method" and thought I explained..

yes in this scenario where the calling class is different from the class where exception has occured, the only way to propagate an error would be by throwing an exception.

vemul

Author

Commented:
I hadn't anticipated starting a debate when I asked the question!  But I have found it interesting and will keep your various views in mind for future reference. :-)  As I understand it, there is a time and place for exceptions, but they should be used wisely.

My thanks to Gkern and Vemul for the practical ideas.  As a result I now have my exception up and running and have been able to go on to experiment with others including multiple catches.  (In view of the debate I hasten to add that the experimentation was a learning exercise, not a attempt at an "exception program"!!! :-) )  I am sorry to have to choose between you for the points, as I learnt from both your suggestions, but I did finally opt for Vemul's approach.

With thanks again and best regards to you all.

And ... hoping a quick personal note, with appreciation for past patience and help, is not breaking the rules ... Hi! objects.  I hope life is well with you.

LRH
Mick BarryJava Developer
Top Expert 2010

Commented:
LRH,

Life is very well thank you.
We just had our 1st child recently which has all been very exciting. Life will never be the same though :-)
Mick BarryJava Developer
Top Expert 2010

Commented:
Just found the following which may be useful:
http://developer.java.sun.com/developer/JDCTechTips/2002/tt0110.html
Mick BarryJava Developer
Top Expert 2010

Commented:

Author

Commented:
Many congratulations.  That's lovely news.
 
Thanks for the links.  I've just had a quick look.  They look helpful ... and the first could perhaps have saved you a few of the FileOutputStream headaches I caused you if you'd found it a few months ago!!! :-)

Wishing you not too many sleepless nights! :-)

LRH

Commented:
Thank you LRH and to everyone's comments

objects, thanks for correcting me. I always appreciate your comments /suggestions.. you're awesome.

vemul
Mick BarryJava Developer
Top Expert 2010

Commented:
No worries :">

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial