Commit eaf9249
committed
feat: Add NegativeValueExceptionDemo to showcase custom exception handling in static method call
WHAT the code does:
- Defines NegativeValueExceptionDemo with a main() method.
- Declares length = -5 and width = 3.
- Calls Rectangle.calculateArea(length, width) directly using the class name (static method call).
- Catches NegativeValueException if thrown, printing its message.
WHY this matters:
- Demonstrates how custom exceptions (NegativeValueException) can be triggered and caught in client code.
- Reinforces that static methods can directly throw exceptions to the caller without requiring an object.
- Provides a realistic case where invalid input (negative dimensions) triggers exception handling.
HOW it works:
1. main() defines invalid dimensions (length = -5).
2. Calls Rectangle.calculateArea(), which checks input.
- If negative, throws NegativeValueException with a descriptive message.
3. The try–catch block in NegativeValueExceptionDemo catches the thrown exception.
4. Prints the error message instead of crashing.
Tips and gotchas:
- Always validate method arguments before processing to avoid logical errors.
- Exception handling separates error-handling logic from normal flow, improving readability.
- Since calculateArea() is static, it should be called with Rectangle.calculateArea(), not via an instance.
Use-cases / analogies:
- Validating user input in forms (e.g., age, salary must be non-negative).
- Preventing invalid dimensions in geometry-related applications.
- Guard clauses in business rules (e.g., minimum balance, positive quantities).
Short key: java custom-exception demo static-method input-validation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d2d79eb commit eaf9249
File tree
1 file changed
+2
-4
lines changed- Section18ExceptionHandling/src
1 file changed
+2
-4
lines changedLines changed: 2 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
| 1 | + | |
| 2 | + | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
| |||
0 commit comments