Skip to main content

Throw vs Throws

The throw and throws keywords are used in Java exception handling, but they serve completely different purposes.


1. The throw Keyword

The throw keyword is used to explicitly throw a single exception from within a method or a block of code.

  • It is typically used to throw custom exceptions or explicitly trigger a runtime exception based on certain conditions (like invalid user input).
  • You can only throw one exception at a time using throw.

Example

public class LabException5 {

static void validateAge(int age) {
if (age < 18) {
// Explicitly throwing an exception
throw new ArithmeticException("Not eligible to vote!");
} else {
System.out.println("Welcome to the voting system.");
}
}

public static void main(String args[]) {
validateAge(16); // This will crash the program with the custom message
}
}

2. The throws Keyword

The throws keyword is used in a method signature to declare that the method might throw one or more exceptions during its execution.

  • It is used primarily for Checked Exceptions to tell the compiler and the caller of the method that they need to handle the exception.
  • It does not actually throw an exception; it delegates the responsibility of handling the exception to the caller method.
  • You can declare multiple exceptions using a comma-separated list.

Example

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class LabException6 {

// Declaring that this method might throw an IOException
static void readFile() throws IOException {
File file = new File("nonexistent_file.txt");
FileReader fr = new FileReader(file); // Might throw FileNotFoundException
}

public static void main(String args[]) {
try {
// The caller MUST handle the checked exception
readFile();
} catch (IOException e) {
System.out.println("Exception handled: File not found.");
}
}
}

Differences: throw vs throws

Here is a side-by-side comparison of the two keywords:

Featurethrowthrows
PurposeUsed to explicitly throw an exception object.Used to declare that a method might throw exceptions.
LocationInside the method body.In the method signature.
Multiple ExceptionsCan throw only one exception at a time.Can declare multiple exceptions (comma-separated).
UsageFollowed by an instance (object) of an Exception class (throw new ArithmeticException()).Followed by the Exception class names (throws IOException, SQLException).
Type of ExceptionMostly used for Custom/Unchecked Exceptions.Must be used for Checked Exceptions.

[!TIP] Think of throw as the action of causing the problem, and throws as a warning label on the method indicating what problems might occur.