Commit 690d444
committed
feat: Implement custom checked exception for validating rectangle dimensions
WHAT the code does:
- Defines Rectangle class:
- calculateArea(int length, int width) throws NegativeValueException.
- Validates inputs: if length or width < 0, throws a custom checked exception.
- Otherwise returns area = length * width.
- Defines NegativeValueException:
- Extends Exception (checked exception).
- Constructor accepts error message and passes it to super().
- Defines CustomExceptions main():
- Initializes length = -5, width = 3.
- Calls calculateArea() inside try–catch.
- Catches NegativeValueException and prints error message.
WHY this matters:
- Demonstrates **custom checked exceptions**:
- Extending Exception requires caller to handle or declare with throws.
- Enforces validation logic at compile-time, ensuring input correctness.
- Validates real-world logic: a rectangle cannot have negative dimensions.
- Shows how to integrate exception handling into normal program flow.
HOW it works:
1. main() sets length = -5, width = 3.
2. calculateArea(-5, 3) detects invalid input.
3. Throws new NegativeValueException("Error: length or width cannot be negative").
4. Exception propagates to main() and is caught in catch block.
5. Prints "Error: length or width cannot be negative".
Tips and gotchas:
- Custom exceptions improve readability and domain-specific error handling.
- Checked vs unchecked:
- Extending Exception (checked) forces handling at compile-time.
- Extending RuntimeException (unchecked) would not require try–catch but shifts responsibility to runtime.
- Prefer meaningful class names: NegativeValueException is clear and domain-specific.
- Avoid unnecessary object instantiation: calculateArea is static, so no need for `new Rectangle()`.
Use-cases / analogies:
- Like form validation: you can’t submit a form with invalid values; exception is thrown.
- In banking: throwing InsufficientFundsException when withdrawal exceeds balance.
Short key: java custom-checked-exception input-validation rectangle-area.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent fe33a72 commit 690d444
1 file changed
+2
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | 1 | | |
3 | 2 | | |
4 | 3 | | |
| |||
16 | 15 | | |
17 | 16 | | |
18 | 17 | | |
19 | | - | |
20 | | - | |
21 | | - | |
22 | | - | |
| 18 | + | |
| 19 | + | |
23 | 20 | | |
24 | 21 | | |
25 | 22 | | |
| |||
0 commit comments