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

  • Scala Programming Projects
  • Mikael Valot Nicolas Jorand
  • 247字
  • 2021-07-23 16:25:24

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.

主站蜘蛛池模板: 芒康县| 泽州县| 沾化县| 铁岭县| 新田县| 金山区| 呼图壁县| 沙坪坝区| 兖州市| 清徐县| 改则县| 洛浦县| 汉沽区| 夏河县| 济宁市| 永寿县| 交城县| 应城市| 满洲里市| 新余市| 武定县| 突泉县| 汤阴县| 凤台县| 遵化市| 伊宁县| 外汇| 仁寿县| 花莲县| 宝坻区| 陵川县| 牙克石市| 久治县| 石狮市| 湖州市| 肃北| 罗甸县| 蒲江县| 胶南市| 屏东县| 平遥县|