Types of Exception in Java with Example

Java is object oriented programming language.There are two types of exception in java.You can define your own exception in java.We will discuss types of exception in Java with example.

 

Types of Exception

Types of Exception:-

Below are types of exception in Java with example.

  • Checked Exception
  • Unchecked Exception
  • Error

Lets discuss types of exception with example.

Checked Exception:-

Compiler detect exception at compile time.If method is throwing checked exception then it should be handle using try-catch block.You can declare exception using throws keyword.

List of Checked Exception Classes.

Following is the list of Java Checked Exceptions Defined in java.lang.

1 ClassNotFoundException

Class not found.

2 CloneNotSupportedException

Attempt to clone an object that does not implement the Cloneable interface.

3 IllegalAccessException

Access to a class is denied.

4 InstantiationException

Attempt to create an object of an abstract class or interface.

5 InterruptedException

One thread has been interrupted by another thread.

6 NoSuchFieldException

A requested field does not exist.

7 NoSuchMethodException

A requested method does not exist.

Lets see an example.

 

package com.javatechexpert;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;


public class Checkedexception {

      public static void main(String args[]) {       

             File file = new File("D://file.txt");

             FileReader fr = new FileReader(file);

          }

}

Output:-

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

            Unhandled exception type FileNotFoundException

at com.javatechexpert.Checkedexception.main(Checkedexception.java:11)

How to handle Checked Exception:-

Throws:-

You can declare exception using throws keyword.

Example:-

package com.javatechexpert;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Checkedexception {

public static void main(String args[]) throws IOException { 
FileInputStream fis = null;
fis = new FileInputStream("F:/file.txt"); 
int k;

while(( k = fis.read() ) != -1) 
{ 
System.out.print((char)k); 
} 
fis.close(); 
}


}

Output:- File data displayed on screen

Try-catch block:-

You can handle checked exception using try-catch block.

package com.javatechexpert;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Checkedexception {

public static void main(String args[]) {
FileInputStream fis = null;
try {
fis = new FileInputStream("F:/file.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("The file does not " + "exist at the location");
}
int i = 0;

try {
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}

fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("I/O error occurred: " + e);
}
}

}

Output:- Display content of file.

Unchecked Exception:-

Unchecked exception means exception occur during execution of program.A runtime exception is called unchecked exception.All unchecked exception are direct subclass of RuntimeException.They are not checked while compiling the program.

List of Unchecked Exception Classes:-

1 ArithmeticException

Arithmetic error, such as divide-by-zero.

2 ArrayIndexOutOfBoundsException

Array index is out-of-bounds.

3 ArrayStoreException

Assignment to an array element of an incompatible type.

4 ClassCastException

Invalid cast.

5 IllegalArgumentException

Illegal argument used to invoke a method.

6 IllegalMonitorStateException

Illegal monitor operation, such as waiting on an unlocked thread.

7 IllegalStateException

Environment or application is in incorrect state.

8 IllegalThreadStateException

Requested operation not compatible with the current thread state.

9 IndexOutOfBoundsException

Some type of index is out-of-bounds.

10 NegativeArraySizeException

Array created with a negative size.

11 NullPointerException

Invalid use of a null reference.

12 NumberFormatException

Invalid conversion of a string to a numeric format.

13 SecurityException

Attempt to violate security.

14 StringIndexOutOfBounds

Attempt to index outside the bounds of a string.

15 UnsupportedOperationException

An unsupported operation was encountered.

Let take example of ArrayIndeOutOfBoundException.

Example:-

package com.javatechexpert;

public class Uncheckedexception {




         public static void main(String args[]) {

             int num[] = {1, 2, 3, 4,5};

             System.out.println(num[6]);

          }

}

Output:-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

            at com.javatechexpert.Uncheckedexception.main(Uncheckedexception.java:7)

You can handle unchecked exception using try-catch block and display error message to user.

 

package com.javatechexpert;

public class Uncheckedexception {

public static void main(String args[]) {
try {

int num[] = {1, 2, 3, 4,5};
System.out.println(num[6]);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Specified index does not exist"+e);
}


}
}

Output:-

Specified index does not existjava.lang.ArrayIndexOutOfBoundsException: 6

Error:-

Error mainly caused by the environment in which application is running.You will not be able to handle with try catch block.It belongs to java.lang.error.Error belongs to unchecked type and mostly occur at runtime.

e.g. OutOfMemoryError,StackOverflowError etc.

Example:-

package com.javatechexpert;

import java.util.Scanner;

public class Uncheckedexception {

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter product price: ");
int price = input.nextInt();
if (price>100){
System.out.println("You can purchase product");

}else {
System.out.println("You can not purchase product");

}


}
}

Output:-

If you enter numeric value then program will execute successfully

Please enter product price: 110
You can purchase product

If user enter string or character then program throw error/exception.

Please enter product price: java
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at com.javatechexpert.Uncheckedexception.main(Uncheckedexception.java:10)

Related Articles:-

Exception Handling in Java

Reference:-

Exceptions

Leave a Reply

%d bloggers like this: