Exception Types in Java
In java, exceptions are mainly categorized into two types, and they are as follows.
- Checked Exceptions
- Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation process to confirm whether the exception is handled by the programmer or not. If it is not handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
- IOException
- FileNotFoundException
- ClassNotFoundException
- SQLException
- DataAccessException
- InstantiationException
- UnknownHostException
🔔 In the exception class hierarchy, the checked exception classes are the direct children of the Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
import java.io.*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:\\Users\\User\\Desktop\\Today\\Sample.txt");
try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}
}
}
When we run the above program, it produces the following output.
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
- ArithmeticException
- NullPointerException
- NumberFormatException
- ArrayIndexOutOfBoundsException
- StringIndexOutOfBoundsException
🔔 In the exception class hierarchy, the unchecked exception classes are the children of RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
public class UncheckedException {
public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
System.out.println(list[6]); //ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
When we run the above program, it produces the following output.
Exception class hierarchy
In java, the built-in classes used to handle exceptions have the following class hierarchy.