Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Issue with Exception Handling.  RSS feed

 
Grant Gibson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 22487
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This throws an exception for dividing by zero. But what do you do when it is a character?
 
Rob Spoor
Sheriff
Posts: 21090
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Marshal
Posts: 55708
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!