diff --git a/lab-03/src/Factorials.java b/lab-03/src/Factorials.java index ea87ae7..94bf047 100644 --- a/lab-03/src/Factorials.java +++ b/lab-03/src/Factorials.java @@ -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; + } + + } } \ No newline at end of file