bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java throw Keyword

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java throw Keyword?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

public ___ Main {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The throw keyword is used to create a custom error.
Definition and Usage
Java throw Keyword

❮ Java Keywords

Example

public class Main {
  static void checkAge(int age) {
    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 throw keyword is used to create a custom error.

The throw statement is used together with an exception type . There are many exception types available in Java: ArithmeticException , ClassNotFoundException , ArrayIndexOutOfBoundsException , SecurityException , etc.

The exception type is often used together with a custom method , like in the example above.

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 this Keyword

Next

Java throws Keyword