What is the difference between throw and throws in Java?
| Point | throw | throws |
|---|---|---|
| Kind | Statement inside a method | Keyword in the method declaration |
| Use | Create and send an exception object | Warn that the method can throw exceptions |
| Followed by | One exception object | One or many exception types |
import java.io.IOException;
public class Main {
static void check(int age) throws IOException { // throws: declaration
if (age < 0) {
throw new IOException("Age can not be negative"); // throw: action
}
System.out.println("Age ok");
}
public static void main(String[] args) {
try {
check(10);
check(-1);
} catch (IOException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
Output
Age ok
Caught: Age can not be negative
See Java Exceptions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |