- 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.
- 網絡教育學習指導
- Application Development with Qt Creator(Second Edition)
- 6G潛在關鍵技術(下冊)
- C++黑客編程揭秘與防范
- 網絡故障現場處理實踐(第4版)
- 物聯網安全與深度學習技術
- HTML5 Game development with ImpactJS
- Building RESTful Web Services with Spring 5(Second Edition)
- 圖解手機元器件維修技巧
- Mastering Dart
- 6G新技術 新網絡 新通信
- The Kubernetes Workshop
- Bonita Open Solution 5.x Essentials
- Practical Web Penetration Testing
- 園區網絡架構與技術