lab-03:
- 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:
parent
27234cf989
commit
729a2d7b92
@ -14,8 +14,8 @@ public class Factorials{
|
||||
try {
|
||||
System.out.println("Factorial(" + val + ") = " + factorial(val));
|
||||
}
|
||||
catch (IllegalArgumentException ex){
|
||||
System.out.println(ex.getMessage() + String.format(" (%d)", val));
|
||||
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) (%s)", val, ex.getClass()));
|
||||
}
|
||||
|
||||
System.out.print("Another factorial? (y/n) ");
|
||||
@ -24,11 +24,30 @@ public class Factorials{
|
||||
}
|
||||
|
||||
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");
|
||||
for (int i = value - 1; i > 0; i--){
|
||||
value *= i;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user