throw
- Java course
- Beginner
- Lesson 108/116
- 4 min
Learn to throw exceptions with throw.
Throw exceptions with throw
The throw keyword deliberately throws an exception. It is used to stop the program and alert the caller when a condition is violated.
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("Negatif yaş");
}new IllegalArgumentException(...) creates an exception object; throw launches it. If the exception is not caught, the program crashes and a stack trace is printed. Writing throw after a condition check is a clean way to stop invalid input early.
Catch and rethrow
Sometimes you need to catch an exception, process it, and then rethrow it. You use throw to throw the caught Exception object again, so the upper layer is also informed.
try {
int r = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Loglandı");
throw e;
}Rethrowing lets the error propagate after logging or a temporary fix. But note: if there is a finally, it still runs. This pattern is useful for layering error handling.
Practice Negative age error
Define int age = -5;. If age < 0, throw new IllegalArgumentException("Negatif yaş"). Wrap everything in try; catch IllegalArgumentException and print Hata: with getMessage().
Starter code
public class Main {
public static void main(String[] args) {
int age = -5;
// check the condition, throw, catch, print a message
}
}Sample solution
try {
if (age < 0) {
throw new IllegalArgumentException("Negatif yaş");
}
} catch (IllegalArgumentException e) {
System.out.println("Hata: " + e.getMessage());
}Expected output
Hata: Negatif yaş
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each expression to its purpose
| Term | Meaning |
|---|---|
throw |
Throws exception |
new IllegalArgumentException |
Creates object |
if (age < 0) |
Condition check |
getMessage() |
Gives description |
2 What does throw new IllegalArgumentException("X") do?
- Declares a variable
- Creates and throws an exception object Correct answer
- Calls a method
- Starts a loop
Explanation: new creates the exception object and throw launches it.
3 Throw for a negative age
if (age < 0) {
____ new IllegalArgumentException("Negatif yaş");
}
if (age < 0) {
throw new IllegalArgumentException("Negatif yaş");
}
Explanation: throw new creates and throws the exception.