Careeroza
throw and throws
Difference
throw | throws | |
|---|---|---|
| What | statement that raises an exception now | part of a method signature |
| Where | inside a method body | after the parameter list |
| Followed by | one exception object: throw new X("msg") | one or more exception types |
| Purpose | signal a problem | warn callers what may be thrown |
Validating Input
Example
public class Main {
static void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Invalid age: " + age);
}
System.out.println("Age set to " + age);
}
static void sleepBriefly() throws InterruptedException {
Thread.sleep(10);
System.out.println("Woke up");
}
public static void main(String[] args) throws InterruptedException {
setAge(25);
try {
setAge(-4);
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
}
sleepBriefly();
}
}Output
Age set to 25 Caught: Invalid age: -4 Woke up
Rethrowing and Exception Chaining
Example
Wrap a low-level exception in a higher-level one and keep the original as the cause. Never lose the cause; it is the most useful part of a stack trace.
public class Main {
static int loadPort(String value) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new IllegalStateException("Invalid server port in config", e);
}
}
public static void main(String[] args) {
try {
loadPort("80a");
} catch (IllegalStateException e) {
System.out.println("Error : " + e.getMessage());
System.out.println("Cause : " + e.getCause());
}
}
}Output
Error : Invalid server port in config Cause : java.lang.NumberFormatException: For input string: "80a"