Web Analytics

Throw and Throws

Intermediate ~20 min read

Java provides the throw keyword to explicitly throw an exception, and the throws keyword to declare an exception.

The 'throw' Keyword

The throw statement allows you to create a custom error. You can throw mostly any exception type (arithmetic, array issue, or custom logic).

if (age < 18) {
  throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}

The 'throws' Keyword

The throws keyword is used in the method signature to declare that this method might throw one of the listed exceptions. The caller of this method must handling these exceptions (using try-catch).

public void checkFile() throws IOException {
  // Code that might cause an input/output error
}
Rule: Checked exceptions (like IOException) MUST be declared with throws or handled with try-catch. Unchecked exceptions (like ArithmeticException) don't require this, but it's good practice to document them.

Full Example

Output
Click Run to execute your code

Summary

  • Use throw implies "Do it now!" (Create an exception).
  • Use throws implies "Watch out!" (Declare it in method header).
  • This mechanism allows errors to bubble up to where they can be handled properly.