Skip to content

Commit 690d444

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

File tree

1 file changed

+2
-5
lines changed

1 file changed

+2
-5
lines changed

Section18ExceptionHandling/src/CustomExceptions.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// Submit to check the output
21
import java.util.*;
32

43
class Rectangle {
@@ -16,10 +15,8 @@ public NegativeValueException(String message) {
1615
}
1716
}
1817

19-
class CustomExceptions
20-
{
21-
public static void main (String[] args)
22-
{
18+
class CustomExceptions {
19+
public static void main (String[] args) {
2320
try {
2421
int length = -5;
2522
int width = 3;

0 commit comments

Comments
 (0)