Exceptions in java
Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.
In Java, an exception is an object that wraps an error event that occurred within a method and contains:.
- Information about the error including its type
- The state of the program when the error occurred
- Optionally, other custom information
Exception objects can be thrown and caught.
JVM Errors:
- OutOfMemoryError
- StackOverflowError
- LinkageError
System errors:
- FileNotFoundException
- IOException
- SocketTimeoutException
Programming errors:
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArithmeticException
Ads by Google


Built-In Exceptions
Many exceptions and errors are automatically generated by the Java virtual machine.
Many exceptions and errors are automatically generated by the Java virtual machine. - Running out of memory
- Infinite recursion
- Inability to link to another class
Runtime exceptions, generally a result of programming errors, such as: - Dereferencing a null reference
- Trying to read outside the bounds of an array
- Dividing an integer value by zero
Example:
public class ExceptionDemo {

public static void main (String[] args) {
System.out.println(divideArray(args));
}

private static int divideArray(String[] array) {
String s1 = array[0];
String s2 = array[1];
return divideStrings(s1, s2);
}

private static int divideStrings(String s1, String s2) {
int i1 = Integer.parseInt(s1);
int i2 = Integer.parseInt(s2);
return divideInts(i1, i2);
}

private static int divideInts(int i1, int i2) {
return i1 / i2;
}
}
Compile and try executing the program as follows:
java ExceptionDemo 100 4
25

java ExceptionDemo 100 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.divideInts(ExceptionDemo.java:20)
at ExceptionDemo.divideStrings(ExceptionDemo.java:16)
at ExceptionDemo.divideArray(ExceptionDemo.java:10)
at ExceptionDemo.main(ExceptionDemo.java:4)

java ExceptionDemo 100 four
Exception in thread "main" java.lang.NumberFormatException: For input string: "four"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ExceptionDemo.divideStrings(ExceptionDemo.java:15)
at ExceptionDemo.divideArray(ExceptionDemo.java:10)
at ExceptionDemo.main(ExceptionDemo.java:4)

java ExceptionDemo 100
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ExceptionDemo.divideArray(ExceptionDemo.java:9)
at ExceptionDemo.main(ExceptionDemo.java:4)
Exception Hirarchy
javac
Checked vs. Unchecked Exceptions
The built-in exceptions in Java are categorized on the basis of whether the exception is handled by the Java compiler or not. Java consists of the following categories of built-in exceptions:
- Checked Exceptions
- Unchecked Exceptions
Checked Exceptions
Checked exceptions are the objects of the Exception class or any of its subclasses excluding the Runtime Exception class. Checked exceptions are the invalid conditions that occur in a Java program due to invalid user input, network connectivity problem, or database problems. For example, java.io.IOException is a checked exception. The IOException exception is thrown whenever an input/output operation is abnormally terminated.

Java uses the try-catch block to handle the checked exceptions. The statements within a program that throw an exception are placed in the try block. You associate an exception-handler with the try block by providing one or more catch handlers immediately after the try block
Exception Cause of Creation
ClassNotFoundException Occurs when the Java run-time system is unable to find the class referred.
IllegalAccessException Occurs when you want to refer a class that is not accessible.
InstantiationException Occurs when you try to create an object of an abstract class or interface.
NoSuchMethodException Occurs when you call a method that does not exist
Unchecked Exceptions
Unchecked exceptions are the run-time errors that occur because of programming errors, such as invalid arguments passed to a public method. The Java compiler does not check the unchecked exceptions during program compilation. For example, if you divide a number by zero, an unchecked or run-time exception is raised.

The following table lists the various unchecked exceptions:
Exception Cause of Creation
ArithmeticException Occurs when you make an arithmetic error, such as dividing a number by zero.
ArrayIndexOutOfBoundsException Occurs when an attempt is made to access an array element beyond the index of the array
ArrayStoreException Occurs when you assign an element to an array that is not compatible with the data type of that array.
ClassCastException Occurs when you assign a reference variable of a class to an incompatible reference variable of another class
IllegalArgumentException Occurs when you pass an argument of incompatible data type to a method.
NegativeArraySizeException Occurs when you create an array with negative size
NullPointerException Occurs when an application tries to use an object without allocating memory to it or calls a method of a null object.
NumberFormatException Occurs when you want to convert a string in an incorrect format to a numeric format.
Exception Handling in Java
Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program.
In the following example code you will see that how the exception handling can be done in java program. This example reads integer number for the variables a. If you enter any other character except number, then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.
Example:
public class ExceptionHandle{
public static void main(String[] args) throws Exception{
try{
int a;
a = Integer.parseInt("test");
}
catch(NumberFormatException ex){
System.out.println(ex.getMessage()+ " is not a numeric value.");
System.exit(0);
}
}
}
Output :
For input string: "test" is not a numeric value.
Previous - Java I/O                                                                      Next - Java Multithreading