September 2018
Intermediate to advanced
398 pages
9h 43m
English
The following is a code snippet that demonstrates how exceptions can be thrown. You can paste it in the Scala console or in a Scala worksheet:
case class Person(name: String, age: Int)case class AgeNegativeException(message: String) extends Exception(message)def createPerson(description: String): Person = { val split = description.split(" ") val age = split(1).toInt if (age < 0) throw AgeNegativeException(s"age: $age should be > 0") else Person(split(0), age)
The createPerson function creates the Person object if the string passed in an argument is correct, but throws different types of exceptions if it is not. In the preceding code, we also implemented our own AgeNegativeException isntance, which is thrown if the age ...
Read now
Unlock full access