Types of Exception
Types of Exception
There are mainly two types of exceptions: checked and unchecked.
- Checked Exception
- Unchecked Exception
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 :-
- EOFException etc.
Note: Compiler forces to the program to write handler in case of checked exception.
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:-
- NegativeArraySizeException etc.
Some common checked and uncheck exception scenarios
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.
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; a=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.