• Post Reply Bookmark Topic Watch Topic
  • New Topic

divide by Zero Exception  RSS feed

 
Will Ashton
Greenhorn
Posts: 27
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I just revised some code I wrote some time ago:







As you can see "amount" isnt assured to be != 0. I did another experiment:



This throws an Exception and halts the program, as expected.



This works just fine. How come?

Greetings
a stunned programmer
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Will Ashton,

Agh, there is a good trap about it.
When you supplied actual literal "0" - correct, it is illegal and it throws an exception.
In second case, you declared "amount" as double. And division by 0.0 is legal. you should get result an "Infinity".

Welcome to Ranch
 
Will Ashton
Greenhorn
Posts: 27
Firefox Browser Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, well. So its about the Double. Thank you
I checked the result and its NaN indeed.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
0/0
Output: RuntimeExceptionArithmeticException:division by zero

10/0
Output: RuntimeExceptionArithmeticException:division by zero

0.0/0.0 = NaN(Not a number)

10/0.0; =Infinity

-10/0.0 = - Infinity (Negative infinity)

 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will Ashton wrote:Oh, well. So its about the Double. Thank you

Not "Double", but "double" in your case. Be strict about it, because these two differs: one is a primitive, the other is object.
You're welcome
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!