From 729a2d7b92ab74a2c9674418a26167733961a962 Mon Sep 17 00:00:00 2001 From: HeshamTB Date: Thu, 15 Oct 2020 07:01:02 +0300 Subject: [PATCH] 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 --- lab-03/src/Factorials.java | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) 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