☄️ throw
– Used to actually throw an exception
✅ What it does:
- Used to manually trigger an exception.
- Can only throw one exception at a time.
- Typically used inside a method or block.
🔧 Syntax:
throw new ExceptionType(“Error message”);
🔍 Example:
class Demo {
public static void validateAge(int age) {
if (age < 18)
throw new IllegalArgumentException("Age must be 18 or above");
System.out.println("Access granted");
}
public static void main(String[] args) {
validateAge(16); // This will throw an exception
}
}
🛡️ throws
– Declares potential exception(s) a method might throw
✅ What it does:
- Used in a method signature to declare that a method might throw one or more exceptions.
- Used for checked exceptions, which must be handled or declared.
🔧 Syntax:
returnType methodName() throws Exception1, Exception2 { }
🔍 Example:
import java.io.*;
class Demo {
public static void readFile(String path) throws IOException {
FileReader file = new FileReader(path);
// Reading logic...
}
public static void main(String[] args) throws IOException {
readFile("nonexistent.txt"); // Might throw IOException
}
}
🧠 Key Differences at a Glance
Feature | throw | throws |
---|---|---|
Purpose | Used to actually throw an exception | Declares possible exceptions |
Location | Inside method or block | In method signature |
Keyword Followed By | Instance of Throwable class | Exception class name(s) |
Throws How Many? | One exception at a time | One or more exception types |
Checked or Unchecked? | Works with both types | Mostly used for checked exceptions |
Causes Exception? | Yes, actively throws | No, just declares |