โ๏ธ 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 |