Scala Exception Handling
Scala's exception handling is similar to other languages like Java.
Scala methods can terminate the execution of relevant code by throwing an exception, rather than having to return a value.
Throwing Exceptions
Scala throws exceptions in the same way as Java, using the throw method. For example, throwing a new IllegalArgumentException:
throw new IllegalArgumentException
Catching Exceptions
The exception catching mechanism is the same as in other languages. If an exception occurs, catch clauses are caught in order. Therefore, in catch clauses, the more specific exceptions should come first, and the more general exceptions should come later. If the thrown exception is not in a catch clause, the exception cannot be handled and will be escalated to the caller.
The syntax of the catch clause for catching exceptions is somewhat different from other languages. In Scala, the idea of pattern matching is borrowed for exception matching. Therefore, in the catch code, there is a series of case clauses, as shown in the following example:
Example
import java.io.FileNotFoundException
import java.io.IOException
object Test {
def main(args: Array[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException =>{
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
}
}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test Missing file exception
The content in the catch clause is exactly the same as the case in match. Since exception catching is sequential, if the most general exception, Throwable, is written first, then the cases after it will not be caught, so it needs to be written last.
finally Statement
The finally statement is used to execute steps that need to be executed regardless of whether processing is normal or an exception occurs. An example is as follows:
Example
import java.io.FileNotFoundException
import java.io.IOException
object Test {
def main(args: Array[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException => {
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
} finally {
println("Exiting finally...")
}
}
}
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test Missing file exception Exiting finally...Other Extensions