Why throw and throws?
Sometimes, you want to:
π Manually throw an exception in your code β use
throwπ Declare that a method might throw an exception β use
throws
Both are useful when you're creating custom logic or delegating exception handling.
ππ» throw Keyword
The throw keyword is used to explicitly throw an exception β either a built-in or a custom one.
π§ Syntax:
throw new ExceptionType("message");β
Example: Using throw
public class Main {
public static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("You can vote");
}
}
public static void main(String[] args) {
checkAge(16); // Manually throwing exception
}
}Exception in thread "main" java.lang.ArithmeticException: Not eligible to voteπΉ Note:
Only one exception can be thrown using throw
throwis followed by a new instance ofThrowable(Exception or subclass)
π· What is Throwable in Java?
Throwable is a class in the java.lang package, and it is the superclass of all errors and exceptions that can be thrown and caught by the Java Virtual Machine (JVM).
In simple terms:
Anything that can be "thrown" as an error or exception in Java must be a subclass of Throwable.
π§ Purpose of Throwable:
To define a common type for all objects that represent problems during program execution.
It allows the use of
try-catchblocks to handle problems in a uniform way.Java's exception-handling mechanism is built on top of the
Throwableclass
ππ» throws Keyword
The throws keyword is used to declare that a method might throw an exception, so the caller should handle it.
π§ Syntax:
returnType methodName() throws ExceptionType {
// method body
}β
Example: Using throws
public class Main {
// This method declares that it might throw an Exception
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("You must be 18 or older");
} else {
System.out.println("Access granted");
}
}
public static void main(String[] args) {
try {
checkAge(15); // This will throw an exception
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}Exception caught: You must be 18 or olderπ throw vs throws β Quick Comparison
Feature | throw | throws |
|---|---|---|
Use Case | Used to actually throw an exception | Used to declare potential exceptions |
Placement | Inside a method | In method signature |
Quantity | Only one exception at a time | Can declare multiple exceptions |
Example |
|
|