官术网_书友最值得收藏!

Throwing exceptions

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 passed in the string is negative, as shown in the following code:

scala> createPerson("John 25")
res0: Person = Person(John,25)

scala> createPerson("John25")
java.lang.ArrayIndexOutOfBoundsException: 1
at .createPerson(<console>:17)
... 24 elided

scala> createPerson("John -25")
AgeNegativeException: age: -25 should be > 0
at .createPerson(<console>:19)
... 24 elided

scala> createPerson("John 25.3")
java.lang.NumberFormatException: For input string: "25.3"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at scala.collection.immutable.StringLike.toInt(StringLike.scala:301)
at scala.collection.immutable.StringLike.toInt$(StringLike.scala:301)
at scala.collection.immutable.StringOps.toInt(StringOps.scala:29)
at .createPerson(<console>:17)
... 24 elided

Since the exceptions are not caught by any try...catch block, the Scala console shows a stack trace. The stack trace shows all the nested function calls that led to the point where the exception was thrown. In the last example, the val age = split(1).toInt line in createPerson called scala.collection.immutable.StringOps.toInt, which called scala.collection.immutable.StringLike.toInt$, and so on, until finally the java.lang.Integer.parseInt function threw the exception at line 580 in Integer.java.

主站蜘蛛池模板: 修武县| 平原县| 昆明市| 陆河县| 卢氏县| 佳木斯市| 城步| 南宫市| 盐亭县| 宝清县| 绥化市| 牟定县| 克什克腾旗| 乌鲁木齐市| 长垣县| 定边县| 怀仁县| 宁津县| 灵宝市| 武宁县| 惠安县| 资阳市| 柞水县| 唐海县| 鄂尔多斯市| 彩票| 河津市| 石城县| 乐昌市| 长顺县| 六枝特区| 隆子县| 贺州市| 汤阴县| 辉县市| 安阳县| 任丘市| 普兰县| 义马市| 伊吾县| 浦城县|