Scala Exceptions in Depth
An exception is a signal that something went wrong while a program runs. It carries a message that explains the problem.
A catch case turns a bad parse into a safe value
The function tries to turn text into a number. A bad text falls into the catch case instead of stopping the program.
def parse(s: String): Int =
try
s.toInt
catch
case e: NumberFormatException => -1
@main def main(): Unit =
println(parse("42"))
println(parse("abc"))The first matching catch case wins
Two tries throw two different problems. Each one lands in its own catch case.
def describe(kind: String): String =
try
if kind == "size" then throw new IllegalArgumentException("bad size")
else throw new RuntimeException("general trouble")
catch
case e: IllegalArgumentException => "caught size problem"
case e: Exception => "caught general problem"
@main def main(): Unit =
println(describe("size"))
println(describe("other"))Finally runs when the try block succeeds
The work prints first. The finally marker prints right after it, even though nothing went wrong.
@main def main(): Unit =
try
println("work done")
finally
println("finally ran")Example
class Shortfall(msg: String) extends Exception(msg)
def withdraw(amount: Int, balance: Int): Int =
if amount > balance then throw new Shortfall("need 30 more")
else balance - amount
@main def main(): Unit =
println(withdraw(30, 100))
try
withdraw(80, 50)
catch
case e: Shortfall => println(e.getMessage)
finally
println("audit done")Key points
- Try block: risky code goes inside a try block.
- Catch case: each catch case names one exception type and says what to do for it.
- Catch order: a specific exception type comes before a general type like Exception.
- Finally block: a finally block runs whether the try block succeeds or fails.
- Custom exception: a class that extends Exception gives a program its own error type.
In this example, Shortfall is a custom exception type that carries a message. The first withdrawal succeeds and prints 70. The second withdrawal is too large, so it throws Shortfall. The catch case prints the message. The finally block prints the audit marker after the catch case.
Note
an exception that no catch case handles stops the program.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does a finally block do?