Scala Exception Handling
Scala's exception handling is similar to other languages such as Java.
A Scala method can terminate the execution of related code by throwing an exception, rather than through a return value.
Throwing an Exception
Scala throws exceptions in the same way as Java, using the throw method; for example, to throw a new IllegalArgumentException:
throw new IllegalArgumentException
Catching an Exception
The mechanism for catching exceptions is the same as in other languages: if an exception occurs, catch clauses are matched in order. Therefore, in catch clauses, more specific exceptions should come earlier and more general ones later. If the thrown exception is not in any catch clause, it cannot be handled and is propagated to the caller.
The syntax of catch clauses for capturing exceptions is somewhat different from other languages. In Scala, the idea of pattern matching is borrowed to match exceptions, so the code in a catch 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
[
String
]
)
{
try
{
val
f
=
new
FileReader
(
"input.txt"
)
}
catch
{
case
ex
:
FileNotFoundException
=>
{
println
(
"Missing file exception"
)
}
case
ex
:
IOException
=>
{
println
(
"IO Exception"
)
}
}
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
Missing file exception
The content of a catch clause is exactly the same as the cases in a match. Since exceptions are caught in order, if the most general exception, Throwable, is written first, none of the cases after it will be matched, so it must be written last.
The finally Statement
The finally statement is used to execute steps that must be performed whether processing is normal or an exception occurs, as shown in the example below:
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..."
)
}
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
Missing file exception
Exiting finally...