Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Issue with Exception Handling. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Issue with Exception Handling." Watch "Issue with Exception Handling." New topic

Issue with Exception Handling.

Grant Gibson

Joined: Nov 24, 2011
Posts: 10
I'm working with a Fraction Class, and I want to make the Fraction Class throw exceptions whenever the user tries to divide by zero. Am I on the right track? Suggestions?

There is much more to this class, but it is a really long code. It was a given class for us to create Exception Handling. I think I can do most of the error detecting in this block of code. Since this is where the fraction is made. If I'm not mistaken.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

No, you aren't on the right track. There are two things to do with an Exception: throw it and catch it. You were asked to do one of those, and you did the other.
Grant Gibson

Joined: Nov 24, 2011
Posts: 10
This throws an exception for dividing by zero. But what do you do when it is a character?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

You mean when you create a Fraction('a', 'b')? Inside the methods, these chars are no longer chars but ints; they have been implicitly cast. Inside your Fraction constructor 'a' and 'b' have been replaced by their int values 97 and 98.

How To Ask Questions How To Answer Questions
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
I think you should beware of calling methods from inside your constructor. Methods called from inside the constructor should be labelled private or final (no need for both), to prevent strange things happening if those methods are overridden in subclasses.
I agree. Here's the link:
subject: Issue with Exception Handling.
It's not a secret anymore!