Scala Try and Catch
An exception is an error signal that a program can catch and handle. A try and catch block catches a failure, so the program can respond and keep running.
A caught error lets the program finish
The text abc cannot become a number, so catch prints a friendly line. The last line still runs afterwards.
@main def main(): Unit =
try
val number = "abc".toInt
println(number)
catch
case e: NumberFormatException => println("Please enter a whole number")
println("Program finished")getMessage shows the error text
The catch case names the exception e. Printing its message shows the exact reason the conversion failed.
@main def main(): Unit =
try
val number = "abc".toInt
println(number)
catch
case e: NumberFormatException => println(e.getMessage)No error means catch is skipped
The text 42 converts with no problem. The catch case never runs, and the program carries on.
@main def main(): Unit =
try
val number = "42".toInt
println(s"Number is $number")
catch
case e: NumberFormatException => println("Please enter a whole number")
println("Still running")Example
@main def main(): Unit =
val inputs = List("10", "abc", "5")
for text <- inputs do
try
val number = text.toInt
println(s"$text becomes $number")
catch
case e: NumberFormatException => println(s"$text is not a number")
println("All inputs checked")Key points
- Exception: an error signal raised when something goes wrong while a program runs.
- try: the block where risky code goes, such as converting text that may not be a number.
- catch: the block with case lines that handle an exception from the try block.
- NumberFormatException: the exception raised when toInt gets text that is not a number.
- getMessage: gives the exception's own message text, which describes the failure.
- Program continues: after catch handles an exception, the lines after the block run as normal.
In this example, the loop converts each text in the list inside a try block. The texts 10 and 5 convert and print their numbers, the text abc raises a NumberFormatException that catch turns into a plain message, and the final line runs after the loop.
Note
A finally block can also be added after catch, and it runs whether or not an exception happened.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What happens after a catch block handles an exception?