-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorialExceptionDemo.java
More file actions
46 lines (39 loc) · 1.77 KB
/
Copy pathFactorialExceptionDemo.java
File metadata and controls
46 lines (39 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class FactorialProcessor {
// Method that accepts the integer and propagates the exception if it's negative
public void acceptInteger(int number) throws IllegalArgumentException {
if (number < 0) {
// Throwing the exception to be handled by the caller
throw new IllegalArgumentException("Factorial is not defined for negative numbers. Value provided: " + number);
} else {
// If positive or zero, call the calculation method
calculateAndDisplayFactorial(number);
}
}
// Method to calculate and display the factorial
private void calculateAndDisplayFactorial(int number) {
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("The factorial of " + number + " is: " + factorial);
}
}
// 2. Main Driver Class (PascalCase)
public class FactorialExceptionDemo {
public static void main(String[] args) {
System.out.println("--- Factorial Exception Handling Demo ---");
FactorialProcessor processor = new FactorialProcessor();
// Testing the try-catch block for handling the propagated exception
try {
// This will succeed
System.out.println("Attempting to calculate factorial of 5:");
processor.acceptInteger(5);
// This will trigger the IllegalArgumentException
System.out.println("\nAttempting to calculate factorial of -3:");
processor.acceptInteger(-3);
} catch (IllegalArgumentException e) {
// Catching the exception propagated from the FactorialProcessor class
System.out.println("Exception Caught in Main Class -> " + e.getMessage());
}
}
}