Java - Checked Exception: Catch or Declare

Introduction

If a piece of code may throw a checked exception, you must do one of the following:

  • Handle the checked exception by placing the piece of code inside a try-catch block.
  • Specify in your method/constructor declaration to throw the checked exception out.

Handle

You can choose to hand the exception

Demo

import java.io.IOException;

public class Main {
  public static char readChar() {
    char c = '\u0000';
    int input = 0;
    try {/*from   w w  w . ja  va 2s  . c  om*/
      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

Throw

You can choose to throw the exception by using a throws clause in the method's declaration.

The general syntax for a throws clause is

<modifiers> <return type> methodName(parameters) throws <List of Exceptions> {
   // Method body
}

For exception

public void m1() throws Exception1, Exception2, Exception3 {
        statement-1; // May throw Exception1
        statement-2; // May throw Exception2
        statement-3; // May throw Exception3
}

You can also mix the two options

public void m1() throws Exception1, Exception3 {
        statement-1; // May throw Exception1

        try {
                statement-2; // May throw Exception2
        }
        catch(Exception2 e){
                // Handle Exception2 here
        }

        statement-3; // May throw Exception3
}

Demo

import java.io.IOException;

public class Main {
  public static char readChar() throws IOException {
    char c = '\u0000';
    int input = 0;
    input = System.in.read();/*  www  .ja v a2s  .c  o  m*/
    if (input != -1) {
      c = (char) input;
    }
    return c;
  }

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

}

Result

Related Topic