English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Other Java topics

Java throw and throws Keywords

In this tutorial, we will learn how to handle exceptions using the throw and throws keywords with the help of examples.

In Java, exceptions can be divided into two types:

  • Unchecked exceptions:They are checked at runtime rather than at compile time, for example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, exceptions under the Error class, and so on.

  • Checked exceptions:Check them at compile time. For example, IOException, InterruptedException, and so on.

Please refer toJava exceptionsTo learn more about checked and unchecked exceptions.

Generally, we do not need to handle unchecked exceptions. This is because unchecked exceptions occur due to programming errors, and it is a good habit to correct them rather than handle them.

Now, this tutorial will focus on how to use throw and throws to handle checked exceptions.

Java throws keyword

We use the throws keyword in the method declaration to declare the types of exceptions that may occur.

The syntax is:

accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 ... {
  // code
}

From the above syntax, we can see that we can use throws to declare multiple exceptions.

Example1Java throws keyword

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    //Code that may throw IOException
    File newFile = new File("test.txt");
    FileInputStream stream = new FileInputStream(newFile);
  }
  try {
    try{
      System.out.println("The remaining code in the try block");
    } catch(IOException e){
      System.out.println(e);
    }
  }
}

Output Result

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

When we run this program, if the file test.txt does not exist, FileInputStream will throw a FileNotFoundException exception that inherits from IOException.

If a method does not handle exceptions, it must specify the types of exceptions that may occur in the throws clause so that higher-level methods in the call stack can handle them or specify them using the throws keyword itself.

The findFile() method specifies that it can throw IOException. The main() method calls this method and handles the thrown exceptions.

Throwing multiple exceptions

This is how we use the throws keyword to throw multiple exceptions.

import java.io.*;
class Main {
  public static void findFile() throws NullPointerException, IOException, InvalidClassException {
    
    // Code that may throw NullPointerException
    … … … 
    // Code that may throw IOException
    … … … 
    // Code that may throw InvalidClassException 
    … … … 
  }
  try {
    try{
      System.out.println("The remaining code in the try block");
    }1{
      System.out.println(e1.getMessage());
    }2{
      System.out.println(e2.getMessage());
    }
  }
}

Here, the findFile() method specifies that it can throw NullPointerException, IOException, and InvalidClassException in its throws clause.

Please note that we have not handled NullPointerException. This is because it is an unchecked exception. It is not necessary to specify it in the throws clause and handle it.

throws keyword with try...catch...finally

There may be several methods that can cause an exception. Writing try...catch for each method will be tedious, and the code will become long and difficult to understand.

When you have checked exceptions that you do not want to catch in the current method (must be handled exceptions), throws is also very useful.

Java throw keyword

The throw keyword is used to explicitly throw an exception.

When an exception is thrown, the flow of program execution shifts from the try block to the catch block. We use the throw keyword in the method.

The syntax is:

throw throwableObject;

A Throwable object is an instance of the Throwable class or a subclass of the Throwable class.

Example2Java throw keyword

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("Attempt to divide by zero");
  }
  try {
    divideByZero();
  }
}

Output Result

Exception in thread "main" java.lang.ArithmeticException: Attempt to divide by zero
    at Main.divideByZero(Main.java:3)
    at Main.main(Main.java:7)
exit status 1

In this example, we explicitly throw ArithmeticException.

Note: ArithmeticException is an unchecked exception. It is usually unnecessary to handle unchecked exceptions.

Example3Throws checked exception

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    public static void main(String[] args) {
  }
  try {
    findFile();
      System.out.println("The remaining code in the try block");
      catch (IOException e) {
    }
      System.out.println(e.getMessage());
    }
  }
}

Output Result

File Not Found

The findFile() method throws an IOException by passing a message to its constructor.

Note that since it is a checked exception, it must be specified in the throws clause.

The method that calls findFile() needs to handle this exception, or specify it using the throws keyword itself.

We have handled this exception in the main() method. When an exception is thrown, the flow of program execution is transferred between the try blocks to catch. Therefore, the remaining code in the try block will be skipped, and the statements in the catch block will be executed.