Scala's exceptions works like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn't actually have checked exceptions.
To handle exceptions use a try{...}catch{...} block like in Java except that the catch block uses matching to identify and handle the exceptions.
Throwing exceptions:
Throwing an exception looks the same as in Java.create an exception object and then throw it with the throw keyword:
throw new IllegalArgumentException
Catching exceptions:
Scala allows to try/catch any exception in a single block and then perform pattern matching against it using case blocks as shown below:
import java.io.FileReader
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")
}
}
}
}
The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn
No comments:
Post a Comment