Javatpoint Logo
Javatpoint Logo

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.

Exceptions can be categorized into two ways:

  1. Built-in Exceptions
    • Checked Exception
    • Unchecked Exception
  2. User-Defined Exceptions
Types of Exception in Java

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

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:

  1. The FileInputStream(File filename) constructor throws the FileNotFoundException that is checked exception.
  2. The read() method of the FileInputStream class throws the IOException.
  3. The close() method also throws the IOException.

Output:

Types of Exception in Java

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:

If we compile and run the code, the errors will disappear, and we will see the data of the file.

Types of Exception in Java

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

We will see a proper error message "File Not Found!" on the console because there is no such file in that location.

Types of Exception in Java

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

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:

Types of Exception in Java

UncheckedException1.java

Output:

Types of Exception in Java

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.

Let's write a Java program and create user-defined exception.

UserDefinedException.java

Output:

Types of Exception in Java

Description:

In the above code, we have created two classes, i.e., UserDefinedException and NewException. The UserDefinedException has our main method, and the NewException class is our user-defined exception class, which extends exception. In the NewException class, we create a variable x of type integer and assign a value to it in the constructor. After assigning a value to that variable, we return the exception message.

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.

Difference Between Checked and Unchecked Exception

S.No Checked Exception Unchecked Exception
1. These exceptions are checked at compile time. These exceptions are handled at compile time too. These exceptions are just opposite to the checked exceptions. These exceptions are not checked and handled at compile time.
2. These exceptions are direct subclasses of exception but not extended from RuntimeException class. They are the direct subclasses of the RuntimeException class.
3. The code gives a compilation error in the case when a method throws a checked exception. The compiler is not able to handle the exception on its own. The code compiles without any error because the exceptions escape the notice of the compiler. These exceptions are the results of user-created errors in programming logic.
4. These exceptions mostly occur when the probability of failure is too high. These exceptions occur mostly due to programming mistakes.
5. Common checked exceptions include IOException, DataAccessException, InterruptedException, etc. Common unchecked exceptions include ArithmeticException, InvalidClassException, NullPointerException, etc.
6. These exceptions are propagated using the throws keyword. These are automatically propagated.
7. It is required to provide the try-catch and try-finally block to handle the checked exception. In the case of unchecked exception it is not mandatory.

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.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA