Friday , April 28 2017
Home / java / Checked and Unchecked Exceptions in Java

Checked and Unchecked Exceptions in Java

 

There are two types of exceptions in Java, namely, checked exceptions and unchecked exceptions. It is also important to know what is the need of handling the exceptions in our daily development. But at present Let’s examine both these types of exceptions and then identify their differences.

Checked and Unchecked Exceptions

Checked Exceptions

Checked exceptions are exceptions that a program is supposed to catch and handle. A checked exception is declared in the source code and indicates the possibility of an exceptional condition that might occur within a block of code.

Checked exceptions are validated by the compiler at compile time. Therefore, these exceptions must conform to the catch or specify requirement. This means that a checked exception must be specified either in a try/catch block or in a method’s throws clause.

Some of the checked exceptions in Java are:

  • IllegalAccessExcception

  • SQLException

  • IOException

  • InstantiationException

  • ClassNotFoundException

  • NoSuchMethodExcception

Checked Exceptions – Using the try/catch Block

One way of declaring checked exceptions in source code is by specifying the program statements you need to monitor within a try/catch block. The exceptions thrown from the try block are handled by the catch block.

The following program reads a file and displays its contents. This program illustrates the use of try/catch blocks to specify checked exceptions.


package com.onlinetutorialspoint.exceptions;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CheckedExceptions {

    public static void main(String args[]) {

        int n;

        FileInputStream fis;

        try {

            fis = new FileInputStream(args[0]);

        } catch (FileNotFoundException e) {

            System.out.println("Unable to open file. Please check file name and path");

            return;

        }

        try {

            do {

                n = fis.read();

                if (n != -1) {
                    System.out.print((char) n);
                }

            } while (n != -1);

        } catch (IOException e) {

            System.out.println("Error while reading file");

        }

        try {

            fis.close();

        } catch (IOException e) {

            System.out.println("Error while closing file");

        }

    }
    

}

 In this program, checked exceptions are specified in three places using the try/catch blocks. In the first try/catch block, there is a possibility of an error when the specified filename is not found. This situation throws a FileNotFoundException that is handled by the catch block.

The second try/catch block handles a situation in which an IO error occurs while reading the file and the third try/catch block handles a situation in which the file cannot be closed. In this way, the three possible exceptions that might occur in the program are checked and handled using try/catch blocks.

Checked Exceptions – Using throws

The second way of declaring checked exceptions in source code is by specifying the throws clause in a method’s declaration. When a method does not handle an exception it throws, you must specify the exception using a throws clause in the method’s declaration. If a method uses a throws clause, the checked exception is thrown out of the method.

The following code illustrates the use of the throws clause to specify checked exceptions.


public void displayList() throws IOException {

        PrintWriter out = new PrintWriter(new FileWriter("DisplayFile.txt"));

        for (int i = 0; i < SIZE; i++) {

            System.out.println("Value at: " + i + " = " + list.get(i));

        }

        out.close();

    }

Though there is a possibility of an IOException occurring within this code, the method does not handle the exception. Therefore, the throws clause is used to specify a checked exception so that invoking methods can handle that exception.

Unchecked Exceptions

Unchecked exceptions are the exceptions that a program does not catch and handle. These exceptions are not validated by the compiler but are identified by the Java run-time system. The compiler does not check whether a method throws or handles an unchecked exception. Therefore, unchecked exceptions are not included in a try/catch block or specified in the throws clause of a method. Unchecked exceptions are errors that violate Java’s rules or the run-time environment’s constraints.

Some of the unchecked exceptions in Java are:

  • ArithmeticException

  • NullPointerException

  • ArrayIndexOutOfBoundsException

  • UnsupportedOperationException

  • IllegalStateException

  • ClassCastException

There are two kinds of unchecked exceptions, namely, error and run time exception.

Error:

Errors are exceptions that occur in the run-time system and are outside the scope of the program. These exceptions throw IOError and cannot be resolved by the program. Some examples of errors are hardware or system malfunction, and stack overflow.

Runtime Exceptions:

RuntimeException is a subclass of the Exception class. It includes exceptions that occur due to logic errors or bugs in a program. Run time exceptions are not handled by the program but are identified by the Java run-time system when the program executes. Some examples of run time exceptions are division by zero and null pointer.

Differences Between Checked and Unchecked Exceptions

Some of the differences between checked and unchecked exceptions are:

  • Checked exceptions are checked by the compiler whereas unchecked exceptions are not checked by the compiler.

  • Checked exceptions must be specified in a try/catch block or using the throws clause whereas unchecked exceptions are not specified in the program.

  • Checked exceptions can cause compilation error if their specification is incorrect whereas unchecked exceptions do not cause compilation error.

  • Checked exceptions are handled by an exception handler in the program whereas unchecked exceptions are handled by the Java run-time system.

  • Checked exceptions have a possibility of recovery allowing the program to continue whereas unchecked exceptions result in program termination.

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Binary Literals Java 7 Example Tutorials

Binary literals is one of the new feature added in Java 7. We already know …

Leave a Reply

Your email address will not be published. Required fields are marked *