Java Throw
The throw statement raises an exception from your own code. It carries an exception object with a message that explains the problem.
Throw and catch an exception
throw raises the exception and the catch block prints its message. The last line proves the program continues.
public class Main {
public static void main(String[] args) {
try {
throw new IllegalArgumentException("Age cannot be negative");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println("Program continues");
}
}A method that guards its input
checkScore throws for a negative score and accepts a valid one. The catch block prints the thrown message.
public class Main {
static void checkScore(int score) {
if (score < 0) {
throw new IllegalArgumentException("Score cannot be negative");
}
System.out.println("Score accepted: " + score);
}
public static void main(String[] args) {
checkScore(80);
try {
checkScore(-3);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}An uncaught throw stops the program
No try block guards this call. The thrown exception stops the program and the runtime prints the error report.
public class Main {
static void checkScore(int score) {
if (score < 0) {
throw new IllegalArgumentException("Score cannot be negative");
}
System.out.println("Score: " + score);
}
public static void main(String[] args) {
checkScore(-3);
System.out.println("Done");
}
}Example
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Must be 18 or older");
}
System.out.println("Entry allowed for age " + age);
}
public static void main(String[] args) {
checkAge(21);
try {
checkAge(15);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
System.out.println("Checks finished");
}
}Key points
- throw raises the exception object written after it.
- new builds the exception object that throw raises.
- IllegalArgumentException suits a value that a method cannot accept.
- A throw inside a method stops that method at once.
- A caller can catch a thrown exception with try and catch.
- getMessage returns the message stored in the exception.
In this example, checkAge accepts the age 21 and prints its line. The call with 15 throws an exception with a message. The catch block prints that message through getMessage. The last line then prints Checks finished.
Note
An uncaught throw stops the program and prints an error report, like any uncaught exception.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does the throw statement do?