This content originally appeared on DEV Community and was authored by rajeshwari rajeshwari
In Java, throw
is a keyword used to explicitly throw an exception. Here’s a breakdown of the what, why, how, and when to use it:
What is throw
in Java?
-
throw
is used to manually trigger an exception during program execution. - It transfers control from the current block of code to the nearest
catch
block that can handle the exception.
throw new IllegalArgumentException("Invalid input");
Why use throw
?
You use throw
to:
- Handle unexpected situations or errors in your code.
- Validate input (e.g., null values, invalid arguments).
- Provide custom error messages or throw custom exceptions.
- Improve code robustness by catching problems early.
How to use throw
in Java?
Syntax:
throw new ExceptionType("Error message");
Example:
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
this.age = age;
}
Note: The object thrown must be of type
Throwable
(i.e.,Exception
or subclass).
Custom Exception Example:
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public void checkSomething(boolean condition) throws MyException {
if (!condition) {
throw new MyException("Condition failed");
}
}
When to use throw
in Java?
Use throw
when:
- You need to stop normal flow due to a problem.
- Input is invalid or violates rules.
- Something unexpected happens (e.g., file not found, null value).
- You are implementing custom business logic exceptions.
Common Mistakes
-
Forgetting
new
when creating the exception:
throw IllegalArgumentException("error"); // ❌ wrong
throw new IllegalArgumentException("error"); // ✅ correct
- Throwing a non-Throwable type:
throw "error"; // ❌ wrong
- Forgetting to declare or handle checked exceptions:
public void riskyMethod() throws IOException {
throw new IOException("Disk not found"); // must declare or handle
}
Would you like an explanation of the difference between throw
and throws
too?
This content originally appeared on DEV Community and was authored by rajeshwari rajeshwari