One of the most common examples used to illustrate exceptions is the “division by zero” example.
Exception in thread “main” java.lang.ArithmeticException: / by zero
I think I’ve seen it in a few Java books, so I’ve always had this impression that it’s never ok to divide a number by zero. Until I started preparing for the SCJP, that is. I ran the code below.

import java.io.*;
 
class TestDivideByZero
{
	public static void main(String[] arg) throws IOException
	{
		System.out.println(1/0.0);	//prints "Infinity"
		System.out.println(1.0/0);	//prints "Infinity"
		System.out.println(-1/0.0);	//prints "-Infinity"
		System.out.println(-1.0/0);	//prints "-Infinity"
		System.out.println(1/0);	//runtime error here
		System.out.println(-1/0);	//runtime error here
	}
}

So what’s up? According to Sun:

Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator / never throws a run-time exception.

Tags:

Related posts:

  1. SCJP Prep – surprising autoboxing behaviour One of the features introduced in Java 5 is autoboxing. Boxing means that we take...
  2. Struts DispatchAction – unspecified method I was going through a tutorial about DispatchAction and trying to define a default page...
  3. Installing PHP 5.2.5 on Windows XP for Tomcat 6.0.13 – Issues resolved I was playing around with the idea of doing a small personal PHP project, and...
  4. Clearing the Sun Certified Java Programmer exam It has nearly been 1 year since I bought the exam voucher for the Sun...
  5. Debugging a JSP compilation problem on Tomcat 6 I was doing some experimentation with Maven and Tomcat 6 when I hit this error....

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>