Scala’s exception handling is similar to other languages such as Java.
Scala’s method can terminate the execution of the relevant code by throwing an exception, without having to return a value. Scala throws an exception in the same way as Java, using the The mechanism of exception catching is the same as in other languages, if anexception occurs Catch abnormal Execute the above code, and the output is as follows: The Execute the above code, and the output is as follows: 8.40.1. Throw an exception #
throw
Method, for example, throw a new parameter exception:throw new IllegalArgumentException
8.40.2. Catch exception #
catch
words are captured in order. Therefore, in
catch
in the sentence, the more specific exception is, the more common the exception is, the more backward the exception is. If the exception thrown is not in the
catch
. The exception cannot be handled and is escalated to the caller.
catch
clause, the grammar is quite different from that in other languages. In Scala, the idea of pattern matching is borrowed to doabnormal matching, so
catch
in the code, is a series of
case
sentence, 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[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException =>{
println("Missing file exception")
}
case ex: IOException => {
println("IO Exception")
}
}
}
}
$ scalac Test.scala
$ scala Test
Missing file exception
catch
content in the sentence is similar to that in the sentence
match
in
case
is exactly the same. Because the exception catch isin order, if the most common exception
Throwable
written at the front and behind it
case
none of them can be captured, so you need to write it at the end. 8.40.3. Finally statement #
finally
statement is used to perform steps that need to be performed regardless of normal processing or when an exception occurs, as an example:Example #
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")
}
} finally {
println("Exiting finally...")
}
}
}
$ scalac Test.scala
$ scala Test
Missing file exception
Exiting finally...