Skip to content

Commit

Permalink
exception exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
ssahayam-zd committed Oct 11, 2023
1 parent 89d3bcd commit 387bc9a
Showing 1 changed file with 36 additions and 10 deletions.
46 changes: 36 additions & 10 deletions src/main/scala/introcourse/level05/ExceptionExercises.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
}


Expand All @@ -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
Expand All @@ -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
}
}

/**
Expand All @@ -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
}
}
}

0 comments on commit 387bc9a

Please sign in to comment.