×

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

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.