pTutorial

New way to learn Programming

Types of Exception

Types of Exception

There are mainly two types of exceptions: checked and unchecked.

  1. Checked Exception
  2. Unchecked Exception

Checked exceptions

Except RuntimeException and Error class, All exceptions are known as Checked exceptions. Checked exceptions are check during the compilation of the program.

Examples of Checked Exceptions :-

  • ClassNotFoundException
  • IllegalAccessException
  • NoSuchFieldException
  • EOFException etc.

Note: Compiler forces to the program to write handler in case of checked exception.

Unchecked Exceptions

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException etc. Unchecked Exceptions are also known as runtime exception

Examples of Unchecked Exceptions:-

  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • NullPointerException
  • NegativeArraySizeException etc.

Some common checked and uncheck exception scenarios

uncheck exception

There are given some scenarios where unchecked exceptions can occur. They are as follows:

1. When will ArithmeticException come.

If we trying to divide any number by zero then ArithmeticException comes.

int num=38/0;
  

2. When will NullPointerException come.

If we have variable with null value and performing any operation using the variable then NullPointerException comes.

String uk=null;  
System.out.println(uk.length());

3. When will ArrayIndexOutOfBoundsException comes.

If you are accessing any value in an array that is not available then ArrayIndexOutOfBoundsException comes.

int arr[]=new int[6];  
a[100]=10; 

4. When will StringIndexOutOfBoundsException come.

The above exception comes when access a string that is not present.

String str="ptutorial.com";
str.charAt(50);

Java Checked Exception

1. When will FileNotFoundException comes.

FileNotFoundException comes when specified path in FileReader() does not found. FileReader() throws a checked exception FileNotFoundException.

      FileReader file = new FileReader("C:\\uk\\abc.txt");

2. When will ClassNotFoundException comes.

ClassNotFoundException comes when we trying to load a class that does not exist.

Class.forName("oracle.jdbc.driver.OracleDriver");

See Also


QUOTES OF THE DAY

Each day provides its own gifts.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER