bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java throws Keyword

❮ Java Keywords

Example

public class Main {
  static void checkAge(int age)
  throws
  ArithmeticException {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
  else {
    System.out.println("Access granted - You are old enough!");
  }
}
public static void main(String[] args) {
  checkAge(15); // Set age to 15 (which is below 18...)
}
}

Definition and Usage

The throws keyword indicates what exception type may be thrown by a method.

There are many exception types available in Java: ArithmeticException , ClassNotFoundException , ArrayIndexOutOfBoundsException , SecurityException , etc.

Differences between throw and throws

throwthrows
Used to throw an exception for a methodUsed to indicate what exception type may be thrown by a method
Cannot throw multiple exceptionsCan declare multiple exceptions
Syntax: throw is followed by an object (new type ) used inside the methodSyntax: throws is followed by a class and used with the method signature
  • throw is followed by an object (new type )
  • used inside the method
  • throws is followed by a class
  • and used with the method signature

Related Pages

Read more about exceptions in our Java Try..Catch Tutorial .

❮ Java Keywords

Previous

Java throw Keyword

Next

Java transient Keyword