Topics Index

Exceptions >
Siva Nookala - 06 Oct 2016
An exception is an abnormal condition that arises in a code sequence at run time. An exception is a run-time error.

For any program the errors could occur at compile-time or at run-time. When we compile using Java Compiler (javac) we get the compile-time errors, but when we run the program using (java) we get the run-time errors. In the programs discussed till now, we had seen various compile-time errors like variable not defined, precision lost, incompatible types or method not found. Similarly we have also seen various run time errors like ArrayIndexOutOfBoundException in Arraylist Access Using Index and NullPointerException in Member Variable In Java.
int marks[] = new int[5];
marks[6] = 77; // Throws ArrayIndexOutOfBoundException
As shown in the above example, if we create an array of size 5, but access an element at index 6, it throws an ArrayIndexOutOfBoundException. This is because JVM does not know where to put that value 77, since the valid indices are from 0 to 4.
int d = 0;
int a = 42 / d;
Similarly, when we divide a number by zero, the value will become Infinite, since Infinite can not be stored in double or int data type, it will throw an ArithmeticException with message as / by zero.

So, it is necessary for Java to throw the exceptions in situations like these. Below is the exception thrown by the previous program when a number is divided by zero. But a non-technical user of this program will have difficult time understanding this exception.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestDivideByZero.main(

So, as programmers we need to handle these exceptions better and show understandable messages to the users. The exceptions handling can be done either by preventing it or processing the exception after it has occurred. The prevention of exceptions is explained in How To Handle An Exception In Java and handling of the exceptions post there occurrence is explained in Exception Handling In Java with Example Program.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.