- Define custom exception class that extends IlleglArg and add a 'value' property
	- Throw different Ex for the 2 problems
	- Print the exception class in output for information
This commit is contained in:
HeshamTB 2020-10-15 07:01:02 +03:00
parent 27234cf989
commit 729a2d7b92
Signed by: Hesham
GPG Key ID: 74876157D199B09E

View File

@ -14,8 +14,8 @@ public class Factorials{
try { try {
System.out.println("Factorial(" + val + ") = " + factorial(val)); System.out.println("Factorial(" + val + ") = " + factorial(val));
} }
catch (IllegalArgumentException ex){ catch (IllegalArgumentException ex){ //use of polymorphism since 'ex' can be an instance of one of two classes
System.out.println(ex.getMessage() + String.format(" (%d)", val)); System.out.println(ex.getMessage() + String.format(" (%d) (%s)", val, ex.getClass()));
} }
System.out.print("Another factorial? (y/n) "); System.out.print("Another factorial? (y/n) ");
@ -24,11 +24,30 @@ public class Factorials{
} }
private static int factorial(int value) throws IllegalArgumentException { private static int factorial(int value) throws IllegalArgumentException {
if (value < 0) throw new IllegalArgumentException("Can not calculate a negative factorial"); if (value < 0) throw new IllegalFactorialException("Can not calculate a negative factorial", value);
if (value > 16) throw new IllegalArgumentException("Can not calculate factorials for value over 16"); if (value > 16) throw new IllegalArgumentException("Can not calculate factorials for value over 16");
for (int i = value - 1; i > 0; i--){ for (int i = value - 1; i > 0; i--){
value *= i; value *= i;
} }
return value; return value;
} }
private static class IllegalFactorialException extends IllegalArgumentException {
private int value;
public IllegalFactorialException(String s, int value) {
super(s);
this.value = value;
}
public IllegalFactorialException(int value) {
this(null, value);
}
public int getIllegalValue() {
return value;
}
}
} }