Commit d7e6f2c
committed
feat: Demonstrate throw vs throws with area calculation example
WHAT the code does:
- Defines a class ThrowThrows to illustrate the difference between `throw` and `throws`.
- area(int l, int b):
- Declares `throws Exception` in method signature.
- If l or b < 0, uses `throw new Exception()` to signal invalid arguments.
- Otherwise, returns the product (area).
- meth1():
- Declares `throws Exception`.
- Calls area(10, 2) and prints the result.
- main():
- Declares `throws Exception` in its signature.
- First, calls meth1() inside a try–catch block to handle exceptions locally.
- Then calls meth1() again without try–catch, allowing any exception to propagate since main is declared to throw.
WHY this matters:
- Demonstrates `throw` vs `throws`:
- `throw`: used inside method body to explicitly throw an exception instance.
- `throws`: used in method signature to declare that method may throw checked exceptions.
- Shows exception propagation:
- Exceptions can be caught where they occur (try–catch).
- Or declared with `throws` to be handled further up the call stack.
- Reinforces best practice that exception handling should be deliberate and consistent.
HOW it works:
1. main() → meth1() → area(10, 2).
2. area() validates input, returns 20, no exception thrown.
3. First call is wrapped in try–catch, prints "Area is: 20".
4. Second call runs directly, prints "Area is: 20" again.
5. If arguments were negative, Exception would be thrown:
- First call would be caught and printed in catch.
- Second call would terminate the program, since it is not caught (but main declares throws Exception).
Tips and gotchas:
- Always use descriptive exception types/messages (e.g., IllegalArgumentException) instead of generic Exception.
- Avoid declaring `throws Exception` at method level in production code; declare specific exceptions instead.
- Methods that validate arguments often throw unchecked exceptions (IllegalArgumentException) rather than checked.
- Declaring `throws` in main is usually discouraged; prefer handling exceptions inside main.
Use-cases / analogies:
- Input validation in geometry apps (length, width must be positive).
- Similar logic applies to banking (balance must be ≥ 0) or inventory systems (quantity ≥ 0).
- Demonstrates controlled failure: either handle locally (try–catch) or bubble up (throws).
Short key: java throw-vs-throws checked-exception propagation validation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 314a653 commit d7e6f2c
1 file changed
+2
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | 3 | | |
5 | 4 | | |
| |||
18 | 17 | | |
19 | 18 | | |
20 | 19 | | |
21 | | - | |
| 20 | + | |
0 commit comments