Types of Exception in Java
Types of Exception in Java
In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions. In this section, we will focus
on the types of exceptions in Java and the differences between the two.
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions
Built-in Exception
Exceptions that are already available in Java libraries are referred to as built-in exception.
These exceptions are able to define the error situation so that we can understand the reason of
getting this error. It can be categorized into two broad categories, i.e., checked
exceptions and unchecked exception.
Checked Exception
Checked exceptions are called compile-time exceptions because these exceptions are checked
at compile-time by the compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer should have to handle the exception; otherwise, the system
has shown a compilation error.
CheckedExceptionExample.java
1. import java.io.*;
2. class CheckedExceptionExample {
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/Hello.txt");
6. int m;
7. while(( m = file_data.read() ) != -1) {
8. System.out.print((char)m);
9. }
10. file_data.close();
11. }
12. }
In the above code, we are trying to read the Hello.txt file and display its data or content on the
screen. The program throws the following exceptions:
Output:
How to resolve the error?
There are basically two ways through which we can solve these errors.
1) The exceptions occur in the main method. We can get rid from these compilation errors by
declaring the exception in the main method using the throws We only declare the
IOException, not FileNotFoundException, because of the child-parent relationship. The
IOException class is the parent class of FileNotFoundException, so this exception will
automatically cover by IOException. We will declare the exception in the following way:
1. class Exception{
2. public static void main(String args[]) throws IOException {
3. ...
4. ...
5. }
If we compile and run the code, the errors will disappear, and we will see the data of the file.
2) We can also handle these exception using try-catch However, the way which we have used
above is not correct. We have to a give meaningful message for each exception type. By doing
that it would be easy to understand the error. We will use the try-catch block in the following
way:
Exception.java
1. import java.io.*;
2. class Exception{
3. public static void main(String args[]) {
4. FileInputStream file_data = null;
5. try{
6. file_data = new FileInputStream("C:/Users/ajeet/OneDrive/Desktop/programs/Hell.tx
t");
7. }catch(FileNotFoundException fnfe){
8. System.out.println("File Not Found!");
9. }
10. int m;
11. try{
12. while(( m = file_data.read() ) != -1) {
13. System.out.print((char)m);
14. }
15. file_data.close();
16. }catch(IOException ioe){
17. System.out.println("I/O error occurred: "+ioe);
18. }
19. }
20. }
We will see a proper error message "File Not Found!" on the console because there is no such
file in that location.
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words, if a program throws an unchecked
exception, and even if we didn't handle or declare it, the program would not give a compilation
error. Usually, it occurs when the user provides bad data during the interaction with the
program.
Note: The RuntimeException class is able to resolve all the unchecked exceptions because of the
child-parent relationship.
UncheckedExceptionExample1.java
1. class UncheckedExceptionExample1 {
2. public static void main(String args[])
3. {
4. int postive = 35;
5. int zero = 0;
6. int result = positive/zero;
7. //Give Unchecked Exception here.
8. System.out.println(result);
9. }
10. }
In the above program, we have divided 35 by 0. The code would be compiled successfully, but
it will throw an ArithmeticException error at runtime. On dividing a number by 0 throws the
divide by zero exception that is a uncheck exception.
Output:
UncheckedException1.java
1. class UncheckedException1 {
2. public static void main(String args[])
3. {
4. int num[] ={10,20,30,40,50,60};
5. System.out.println(num[7]);
6. }
7. }
Output:
In the above code, we are trying to get the element located at position 7, but the length of the
array is 6. The code compiles successfully, but throws the ArrayIndexOutOfBoundsException
at runtime.
User-defined Exception
In Java, we already have some built-in exception classes
like ArrayIndexOutOfBoundsException, NullPointerException,
and ArithmeticException. These exceptions are restricted to trigger on some predefined
conditions. In Java, we can write our own exception class by extends the Exception class. We
can throw our own exception on a particular condition using the throw keyword. For creating
a user-defined exception, we should have basic knowledge of the try-catch block
and throw keyword.
UserDefinedException.java
1. import java.util.*;
2. class UserDefinedException{
3. public static void main(String args[]){
4. try{
5. throw new NewException(5);
6. }
7. catch(NewException ex){
8. System.out.println(ex) ;
9. }
10. }
11. }
12. class NewException extends Exception{
13. int x;
14. NewException(int y) {
15. x=y;
16. }
17. public String toString(){
18. return ("Exception value = "+x) ;
19. }
20. }
Output:
Description:
In the UserDefinedException class, we have added a try-catch block. In the try section, we
throw the exception, i.e., NewException and pass an integer to it. The value will be passed to
the NewException class and return a message. We catch that message in the catch block and
show it on the screen.
1. These exceptions are checked at compile These exceptions are just opposite to the
time. These exceptions are handled at checked exceptions. These exceptions are not
compile time too. checked and handled at compile time.
2. These exceptions are direct subclasses of They are the direct subclasses of the
exception but not extended from RuntimeException class.
RuntimeException class.
3. The code gives a compilation error in the The code compiles without any error because
case when a method throws a checked the exceptions escape the notice of the
exception. The compiler is not able to compiler. These exceptions are the results of
handle the exception on its own. user-created errors in programming logic.
4. These exceptions mostly occur when the These exceptions occur mostly due to
probability of failure is too high. programming mistakes.
5. Common checked exceptions include Common unchecked exceptions include
IOException, DataAccessException, ArithmeticException, InvalidClassException,
InterruptedException, etc. NullPointerException, etc.
6. These exceptions are propagated using the These are automatically propagated.
throws keyword.
7. It is required to provide the try-catch and In the case of unchecked exception it is not
try-finally block to handle the checked mandatory.
exception.
Bugs or errors that we don't want and restrict the normal execution of the programs are referred
to as exceptions.
ArithmeticException,ArrayIndexOutOfBoundExceptions,
ClassNotFoundExceptions etc. are come in the category of Built-in Exception. Sometimes,
the built-in exceptions are not sufficient to explain or describe certain situations. For describing
these situations, we have to create our own exceptions by creating an exception class as a
subclass of the Exception class. These types of exceptions come in the category of User-
Defined Exception.