From 387bc9af4faf4aa83463fd304cc4251863aa319b Mon Sep 17 00:00:00 2001 From: "sanjiv.sahayam" Date: Wed, 11 Oct 2023 12:14:24 +1100 Subject: [PATCH] exception exercises --- .../level05/ExceptionExercises.scala | 46 +++++++++++++++---- 1 file changed, 36 insertions(+), 10 deletions(-) diff --git a/src/main/scala/introcourse/level05/ExceptionExercises.scala b/src/main/scala/introcourse/level05/ExceptionExercises.scala index 5624bc19..92cf6c55 100644 --- a/src/main/scala/introcourse/level05/ExceptionExercises.scala +++ b/src/main/scala/introcourse/level05/ExceptionExercises.scala @@ -43,7 +43,11 @@ object ExceptionExercises { * * Hint: use the isEmpty method on String */ - def getName(providedName: String) : String = ??? + def getName(providedName: String) : String = { + if (providedName.isEmpty()) { + throw new EmptyNameException("provided name is empty") + } else providedName + } /** * Implement the function getAge, so that it either accepts the supplied age @@ -64,9 +68,12 @@ object ExceptionExercises { */ def getAge(providedAge: String) : Int = try { - ??? + val age = providedAge.toInt + if (age >= 1 && age <= 120) { + age + } else throw new InvalidAgeRangeException(s"provided age should be between 1-120: $age") } catch { - case _: NumberFormatException => ??? + case _: NumberFormatException => throw new InvalidAgeValueException(s"provided age is invalid: $providedAge") } @@ -92,7 +99,9 @@ object ExceptionExercises { * * Hint: Use `getName` and `getAge` from above. */ - def createPerson(name: String, age: String): Person = ??? + def createPerson(name: String, age: String): Person = { + Person(getName(name), getAge(age)) + } /** * Implement the function createValidPeople to create a List of Person instances @@ -107,15 +116,20 @@ object ExceptionExercises { * What issues do you run into (if any)? */ def createValidPeople: List[Person] = { - personStringPairs.map { + val maybePeople: List[Option[Person]] = personStringPairs.map { case (name, age) => try { - ??? + Some(createPerson(name, age)) // Person } catch { - case _: EmptyNameException => ??? - //handle in any other exception here + case _: EmptyNameException => None + case _: InvalidAgeValueException => None + case _: InvalidAgeRangeException => None } } + + maybePeople.collect { + case Some(person) => person + } } /** @@ -134,8 +148,20 @@ object ExceptionExercises { * What issues do you run into (if any)? */ def collectErrors: List[Exception] = { - personStringPairs.map { - case (name, age) => ??? + val maybeErrors: List[Option[Exception]] = personStringPairs.map { + case (name, age) => + try { + createPerson(name, age) + None + } catch { + case e: EmptyNameException => Some(e) + case e: InvalidAgeValueException => Some(e) + case e: InvalidAgeRangeException => Some(e) + } + } + + maybeErrors.collect { + case Some(error) => error } } }