The throw
operator is used in Java to forcibly throw an exception.
1. The throw
Operator
✅ Purpose:
The throw
keyword is used to manually trigger an exception in Java.
✅ Syntax:
throw new ExceptionType("Error message");
ExceptionType
must be a subclass ofThrowable
(e.g.,Exception
,RuntimeException
).- The
throw
statement must be followed by an exception object.
✅ Example: Throwing an Exception Manually
public class ThrowExample {
public static void main(String[] args) {
throw new RuntimeException("This is a forced exception");
}
}
🛑 Output:
Exception in thread "main" java.lang.RuntimeException: This is a forced exception
2. throw
vs. throws
🔹 throw
(single exception, inside method)
- Used inside a method to forcefully throw an exception.
- Requires an instance of
Throwable
(e.g.,new Exception("Error")
).
🔹 throws
(declaration, multiple exceptions)
- Used in method signatures to declare exceptions a method might throw.
- Multiple exceptions can be declared, separated by commas.
✅ Example: throw
vs. throws
class Example {
// Declaring an exception using throws
public static void riskyMethod() throws IllegalAccessException {
throw new IllegalAccessException("Access denied!"); // Forcing an exception
}
public static void main(String[] args) {
try {
riskyMethod();
} catch (IllegalAccessException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
3. Using throw
with Custom Exceptions
You can create and throw custom exceptions using throw
.
✅ Example: Custom Exception with throw
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
public class CustomThrowExample {
public static void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be at least 18");
}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (AgeException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
🛑 Output:
Caught: Age must be at least 18
Final Thoughts
✔ Use throw
to manually trigger exceptions.
✔ Use throws
to declare exceptions in method signatures.
✔ Always throw an instance of Throwable
or its subclasses.