throw & throwsIn Java, throw and throws are used to handle exceptions manually and declare possible exceptions. They help control error flow and make programs more reliable.
throw creates an exception objectthrows passes responsibility to the callerthrow: Used within method body.
throws: Used in method declaration.
throw
// Demonstrates throwing an exception manually
public class ThrowExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("Eligible to vote");
}
}
throws
// Demonstrates declaring exception using throws
import java.io.*;
public class ThrowsExample {
static void readFile() throws IOException {
FileReader fr = new FileReader("data.txt");
fr.close();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("File not found");
}
}
}
In the first example, the program stops and throws an exception when age is less than 18. In the second example, the method declares a possible exception and the caller handles it using try-catch.
Simulate how the Java logic flows. Enter an age below to test the throw keyword behavior.
throw for custom validationsthrows when method cannot handle exception