Java - Checked and Unchecked Exceptions

Exception Type

  • checked exceptions.
  • unchecked exceptions.

The Throwable class are checked exceptions.

The Throwable class, the Exception class, and subclasses of the Exception class, excluding the RuntimeException class and its subclasses, are called checked exceptions.

They are called checked exceptions because the compiler checks that they are handled in the code.

All exceptions that are not checked exceptions are called unchecked exceptions.

The Error class, all subclasses of the Error class, the RuntimeException class, and all its subclasses are unchecked exceptions.

They are called unchecked exceptions because the compiler does not check if they are handled in the code.

You are free to handle them.

The program for handling a checked or an unchecked exception is the same.

A ReadInput Class Whose readChar() Method Reads One Character from the Standard Input

Demo

import java.io.IOException;

public class Main {
  public static char readChar() {
    char c = '\u0000';
    int input = 0;
    try {/* w w  w  .j  a va  2s. c o  m*/
      input = System.in.read();
      if (input != -1) {
        c = (char) input;
      }
    } catch (IOException e) {
      System.out.print("IOException occurred while reading input.");
    }
    return c;
  }

  public static void main(String[] args) {
    System.out.print("Enter some text and press Enter key: ");
    char c = readChar();
    System.out.println("First character you entered is: " + c);
  }
}

Result

Related Topics