Java Docs

Java Documentation

Java throw and throws

In Java, exceptions can be categorized into two types:

  • Unchecked Exceptions: Not checked at compile-time but at runtime. Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.
  • Checked Exceptions: Checked at compile-time. Examples: IOException, InterruptedException.

Unchecked exceptions usually do not need to be handled — fix the programming errors instead.

Java throws Keyword

The throws keyword is used in a method declaration to specify exceptions that might occur within it.

import java.io.*;

class Main {
  public static void findFile() throws IOException {
    File newFile = new File("test.txt");
    FileInputStream stream = new FileInputStream(newFile);
  }

  public static void main(String[] args) {
    try {
      findFile();
    } catch(IOException e) {
      System.out.println(e);
    }
  }
}

Output

java.io.FileNotFoundException: test.txt (No such file or directory)

You can also declare multiple exceptions with throws:

import java.io.*;

class Main {
  public static void findFile() throws NullPointerException, IOException, InvalidClassException {
    // code that may throw exceptions
  }

  public static void main(String[] args) {
    try {
      findFile();
    } catch(IOException e1) {
      System.out.println(e1.getMessage());
    } catch(InvalidClassException e2) {
      System.out.println(e2.getMessage());
    }
  }
}

Java throw Keyword

The throw keyword is used to explicitly throw a single exception.

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("Trying to divide by 0");
  }

  public static void main(String[] args) {
    divideByZero();
  }
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
    at Main.divideByZero(Main.java:3)
    at Main.main(Main.java:7)

Throwing Checked Exception

import java.io.*;

class Main {
  public static void findFile() throws IOException {
    throw new IOException("File not found");
  }

  public static void main(String[] args) {
    try {
      findFile();
      System.out.println("Rest of code in try block");
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

Output

File not found

In the above example, the checked exception IOException must be declared with throws and handled with a try...catch block.