throw and throws in exception handling
🔹 throw Keyword in Java
The throw keyword is used to explicitly throw an exception from a method or block of code.
✅ Syntax:
✅ Key Points:
-
You can throw only one exception at a time using
throw. -
You must throw an object of type
Throwable(or subclass likeException,RuntimeException, etc.). -
Common for manual exception generation.
📘 Example 1: Using throw with unchecked exception
🔸 Output:
🔹 throws Keyword in Java
The throws keyword is used in method declarations to indicate that a method may throw one or more exceptions.
✅ Syntax:
✅ Key Points:
-
Used with checked exceptions.
-
Propagates the responsibility to handle the exception to the caller.
📘 Example 2: Using throws with checked exception
🔸 Output (if file not found):
If you don't handle or declare the checked exception, the compiler will throw an error.
✅ Differences between throw and throws
| Feature | throw | throws |
|---|---|---|
| Purpose | To explicitly throw an exception | To declare exceptions that a method might throw |
| Used in | Inside method body | In method signature |
| Can throw | One exception at a time | Multiple exceptions (comma separated) |
| Example | throw new IOException(); | void read() throws IOException |
📘 Example 3: Combining throw and throws
🔸 Output:
Comments
Post a Comment