Scala Exception Handling
# Scala Exception Handling
Scala's exception handling is similar to other languages like Java.
Scala methods can terminate the execution of related code by throwing exceptions, rather than relying on return values.
* * *
## Throwing Exceptions
The way Scala throws exceptions is the same as in Java, using the throw keyword. For example, throwing a new argument exception:
throw new IllegalArgumentException
* * *
## Catching Exceptions
The mechanism for catching exceptions is the same as in other languages; if an exception occurs, the catch clauses catch it in order. Therefore, in the catch clause, the more specific exceptions should come first, and the more general exceptions should come later. If the thrown exception is not in the catch clause, the exception cannot be handled and will be escalated to the caller.
The syntax for the catch clause is somewhat different from other languages. In Scala, it borrows the concept of pattern matching to match exceptions. Therefore, within the catch block, there is a series of case clauses, as shown in the following example:
## Example
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Test {
def main(args: Array){
try{
val f =new FileReader("input.txt")
}catch{
case ex: FileNotFoundException =>{
println("Missing file exception")
}
case ex: IOException =>{
println("IO Exception")
}
}
}
}
Executing the above code, the output result is:
$ scalac Test.scala $ scala TestMissing file exception
The content in the catch clause is exactly the same as the case in a match. Since exception catching is in order, if the most general exception, Throwable, is written first, the cases after it will not be caught, so it needs to be written last.
* * *
## The finally Statement
The finally statement is used to execute steps that need to be performed whether the processing is normal or an exception occurs. An example is as follows:
## Example
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Test {
def main(args: Array){
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...")
}
}
}
Executing the above code, the output result is:
$ scalac Test.scala $ scala TestMissing file exception Exiting finally...
YouTip