- 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.
- 黑客攻防實(shí)戰(zhàn)技術(shù)完全手冊(cè):掃描、嗅探、入侵與防御
- 物聯(lián)網(wǎng)工程規(guī)劃技術(shù)
- 物聯(lián)網(wǎng)+BIM:構(gòu)建數(shù)字孿生的未來
- 中小型局域網(wǎng)組建、管理與維護(hù)實(shí)戰(zhàn)
- 網(wǎng)管工具使用與技巧大全
- 網(wǎng)絡(luò)設(shè)計(jì)與應(yīng)用(第2版)
- 通信十年:擁抱互聯(lián)網(wǎng)
- 網(wǎng)管第一課:網(wǎng)絡(luò)操作系統(tǒng)與配置管理
- 物聯(lián)網(wǎng)工程概論
- 信息技術(shù)安全評(píng)估準(zhǔn)則:源流、方法與實(shí)踐
- Cisco無線局域網(wǎng)配置基礎(chǔ)
- 算力網(wǎng)絡(luò):云網(wǎng)融合2.0時(shí)代的網(wǎng)絡(luò)架構(gòu)與關(guān)鍵技術(shù)
- 互聯(lián)網(wǎng)視覺設(shè)計(jì)(全彩慕課版)
- 深入淺出計(jì)算機(jī)網(wǎng)絡(luò)
- 天下一家:網(wǎng)絡(luò)聯(lián)通世界(科學(xué)新導(dǎo)向叢書)