Skip to content

Commit eaf9249

Browse files
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

1 file changed

+2
-4
lines changed

Section18ExceptionHandling/src/NegativeValueExceptionDemo.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
class NegativeValueExceptionDemo
2-
{
3-
public static void main (String[] args)
4-
{
1+
class NegativeValueExceptionDemo {
2+
public static void main (String[] args) {
53
try {
64
int length = -5;
75
int width = 3;

0 commit comments

Comments
 (0)