3.16. Matching One or More Exceptions with try/catch
Problem
You want to catch one or more exceptions in a
try
/catch
block.
Solution
The Scala
try
/catch
/finally
syntax is similar to Java, but it uses the match expression approach in
the catch
block:
val
s
=
"Foo"
try
{
val
i
=
s
.
toInt
}
catch
{
case
e
:
Exception
=>
e
.
printStackTrace
}
When you need to catch and handle multiple exceptions, just add
the exception types as different case
statements:
try
{
openAndReadAFile
(
filename
)
}
catch
{
case
e
:
FileNotFoundException
=>
println
(
"Couldn't find that file."
)
case
e
:
IOException
=>
println
(
"Had an IOException trying to read that file"
)
}
Discussion
As shown, the Scala match expression syntax is used to match different possible exceptions. If you’re not concerned about which specific exceptions might be thrown, and want to catch them all and do something with them (such as log them), use this syntax:
try
{
openAndReadAFile
(
"foo"
)
}
catch
{
case
t
:
Throwable
=>
t
.
printStackTrace
()
}
You can also catch them all and ignore them like this:
try
{
val
i
=
s
.
toInt
}
catch
{
case
_:
Throwable
=>
println
(
"exception ignored"
)
}
As with Java, you can throw an exception from a catch
clause, but because Scala doesn’t have
checked exceptions, you don’t need to specify that a method throws the
exception. This is demonstrated in the following example, where the
method isn’t annotated in any way:
// nothing required here
def
toInt
(
s
:
String
)
:
Option
[
Int
]
=
try
{
Some
(
s
.
toInt
)
}
catch
{
case
e
:
Exception
=>
throw ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.