Java Exception

May 13, 2013 | Java General
A language Learner thinks if his program compiles, he is sure of getting output. Ofcourse, he is right as he is at the beginning of learning. By the time he completes learning, he understands what is Java Exception and why his program does not run and give output even when successfully compiled.

Let us go into the subject. Even if a program compiles, it is not guaranteed of output as at runtime also problems may arise that may prevent the execution. This all of a sudden problem caused at runtime is known as exception.

First let us see an example on Java Exception and then discuss further.
public class Demo
  public static void main(String args[])
    int a = 10, b = 0, c;
    System.out.println("Hello 1");
    c = a/b;

    System.out.println("Hello 2");
    System.out.println("Hello 3");

Java ExceptionOutput screen on Java Exception

See the output screenshot. You see only Hello 1 but not Hello 2 and Hello 3. What happened to them. Why they are not printed.

c = a/b; System.out.println(c);

c = a/b becomes 10/0. 0 division is is undefined (but not 0). At this point, JVM does not know what is to be assigned to c variable. When unknown, JVM simply terminates the execution. This runtime problem is known as exception. The runtime problem is caused by division by zero. Imagine values for a and b are taken from Keyboard or GUI at runtime.

Every runitem problem is represented by a class in Java. The class representing division by zero is ArithmeticException from java.lang package.

Now how to handle the exception thrown by JVM so that Hello 2 and Hello 3 are also printed is known as exception handling.

Would you like to know all the 5 styles of creating Java object without using new keyword?