×

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions.

Exception

An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime.

It indicates some unusual event. Usually, it might be an error. In Java, an exception is dealt with by utilizing the following keywords

  • try
  • catch
  • throw
  • throws
  • finally
  •  RuntimeException: a particular case of this kind addresses a programming error, and ordinarily, we shouldn't throw and catch runtime exemptions. NullPointerException is a very notable runtime particular case in Java. Up to this point, we have Error and Exception that may be RuntimeException or compile time and then addresses three types of errors and exceptions in JDK. Under the errors and exceptions, there are a ton of subclasses. For instance, the IOException addresses an overall I/O mistake and subclass. FileNotFoundException is a more specific case showing a record can't be situated on the circle. That is the way Java exemption API is coordinated.

There are two types of exceptions involved in a java programming language:

  1. Checked exceptions
  2. Unchecked exceptions

Checked Exceptions

Checked exceptions are checked at compile time of the program. In a program, if some part of the code throws an error or exception, it must throw it to the console by using the throws keyword or handle the exception handling keywords.

Checked exceptions are further classified into two types:

  • Fully checked exceptions:

A fully checked exception is reviewed by child classes, like IOException, and InterruptedException.

  • Partially checked exceptions:

 A partially checked exception is an exception in which the few child classes are unchecked like an exception.

These exceptions are categorized as checked exceptions and grouped by package.

The following are the few exceptions involved or defined in the Java.lang package:

  • I/O Exception
  • ClassnotFound Exception
  • Socket Exception
  • SQL Exception
  • CloneNotSupportedException
  • InterruptedException

Similarly, we will get more checked exceptions in java.net, java.SQL, etc. packages.

Here is an example program of Checked exception. Initially, we will check whether we are getting an exception and then try to handle that exception.

For instance, consider the Java program that opens the file from the local storage which has the “C:\\Users\\malip\\jp\\test.txt” path and prints the first two lines of it. The below program doesn't compile since the main method uses FIleReader and throws a FileNotFoundException, one of the checked exceptions. But again, it throws two more exceptions of IOException because of readLine and close methods.

Code:

import java.io.*;
class Tutorialandexample {
// Main method
public static void main(String s[]) 
{
// Reading file from the local directory
FileReader f = new FileReader("C:\\Users\\malip\\jp\\test.txt");
BufferedReader br = new BufferedReader(f);
// Printing the first two lines of the file 
for (int counter = 0; counter < 2; counter++)
System.out.println(br.readLine());
// Closing file 
br.close();
}
}

Input:

test.txt
Welcome to Tutorialandexample.
Today, we will discuss checked exceptions.

Output:

Checked vs Unchecked Exceptions in Java

To resolve the above program, we either need to specify the throws block or must handle it by try and catch block. In the below program, we have used throws to handle the exception. Generally, the obtained exception is a FileNotFoundException. Still, as it is a subclass of IOException, we can declare IOException in the throws list to make the above program compiler-error-free.

Program:

// Java program to Handle  FileNotFoundException 
import java.io.*;
class Tutorialandexample {
// Main method
public static void main(String s[]) throws IOException 
{
// Reading file from the local directory
FileReader f = new FileReader("C:\\Users\\malip\\jp\\test.txt");
BufferedReader br = new BufferedReader(f);
// Printing the first two lines of the file 
for (int counter = 0; counter < 2; counter++)
System.out.println(br.readLine());
// Closing file 
br.close();
}
}

Input:

test.txt
Welcome to Tutorialandexample.
Today, we will discuss checked exceptions.

Output:

Checked vs Unchecked Exceptions in Java

Unchecked Exceptions

Unchecked exceptions are the exceptions that are not checked at compile time. In compiled languages, all acquired exceptions are unchecked, so it is not mandatory for the compiler to handle or specify the exception. It is based on the programmers developing and determining or catching exceptions.

These exceptions are categorized based on the packages. The below mentioned are standard unchecked exceptions in Java.

  • ArithmeticException
  • NumberFormatException
  • IndexOutOfBoundsException
    • ArrayIndexOutOfBoundsException
    • StringIndexOutOfBoundsException
  • NegativeArraySizeException
  • NullPointerException
  • SecurityException

Similarly, we will get more Unchecked exceptions in java.net, java.sql, etc. packages.

Program:

// Java Program for Un-checked Exceptions
           class Tutorialandexample
             {
            // Main method
               public static void main(String s[])
           {
                 int x = 0;
               int y = 10;
              int z = y / x;
               System.out.println(z);
}
}

Output:

Checked vs Unchecked Exceptions in Java

In the above output, we can see that the program is successfully compiled, but at the run time, we got an ArithmeticException, one of the Unchecked exception types.


Related Topics

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.