1. throw Keyword (Exception Throwing)
throw
keyword se hum manually ek specific exception object ko throw karte hain jisse program execution turant ruk jata hai aur nearest matching catch block ko control pass hota hai.
Ye runtime me ek exception ko generate karne ke liye use hota hai.
Example:
public class ThrowExample {
static void validate(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
} else {
System.out.println("Valid age");
}
}
public static void main(String[] args) {
validate(15); // Throws IllegalArgumentException
System.out.println("End of program");
}
}
Is example me agar age 18 se kam hogi to IllegalArgumentException
manually throw kiya jayega jo program ko interrupt karega.
2. throws Keyword (Exception Declaration)
throws
keyword method ki declaration me use hota hai jisme method ke dwara throw kiye gaye exceptions ko specify kiya jata hai.
Isse Java compiler ko pata chalta hai ki caller ko un exceptions ka handling karna hoga ya unhe propagate karna hoga.
Example:
import java.io.*;
public class ThrowsExample {
static void readFile() throws IOException {
FileReader file = new FileReader("textfile.txt");
file.close();
}
public static void main(String[] args) {
try {
readFile(); // IOException can be thrown here
} catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Yahan readFile
method ke signature me throws IOException
diya hai taaki caller is exception ko handle ya propagate kare.
3. Major Differences Between throw and throws
Aspect | throw | throws |
---|---|---|
Purpose | Explicitly throws a single exception from a method/block | Declares multiple exceptions a method might throw |
Usage Location | Inside method or block | Method signature declaration |
Exception Handling | Controls the flow by throwing exception to nearest catch | Informs caller to handle or declare exceptions |
Number of Exceptions | One exception at a time | Multiple exceptions separated by commas |
Exception Types | Checked and Unchecked exceptions | Usually Checked exceptions |
Effect on Program Flow | Interrupts normal flow | Does not interrupt flow, only declaration |
4. Best Practices
- Only throw exceptions when truly exceptional situations occur.
- Use throws in method signature to document possible exceptions for maintainability.
- Catch and handle exceptions higher up the call stack, not necessarily close to where they occur.
- Avoid throwing generic Exception class; specify precise exception types.
- Always clean up resources in finally blocks or use try-with-resources.