• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exceptions  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting unexpected output,how come "trying to divide by zero " is not displayed?,When I divide by 0 I get to the catch block with throws ("trying to divide by zero") but when I come back to my main method I would expect that first it would throw that error in the divide method and not in the main method's catch block.

any reason(s) why this happens ?

thanks

 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you divide by zero in the divide() method, that division causes an ArithmeticException to be thrown, which the divide() method explicitly catches.
You then throw a new ArithmeticException with the text "trying to divide by 0".

The main() method catches that exception. In the catch-clause you ignore that exception and print "did not work".
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your exception is caught right where it is supposed to be caught in the divide method, but all you do is immediately throw it again, so of course it's going to be caught at the previous level's exception handler.  Do something in your catch before you rethrow the exception and you'll see you actually enter that catch block in the divide method.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:. . . immediately throw it again . . .
[Nasty pedantic mode]Well, actually throw another, similar, Exception.[/Nasty pedantic mode]
 
Adam Chalkley
Ranch Hand
Posts: 518
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys makes sesne =)
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!