Exceptions happen often in Scala program development. A program fails, a stack trace appears, and nothing further happens in the program.
With exception handling, we trap and process these exceptions. Our programs can continue as though they were never stopped. In Scala we use keywords: try, catch, throw.
This program uses a try
-construct. Its division expression will cause an ArithmeticException
to occur. The catch block is entered.
object Program { def main(args: Array[String]): Unit = { try { // Try to perform an impossible operation. val mistake = 1 / 0 } catch { // Handle exceptions. case npe: NullPointerException => println(s"Result NPE: $npe") case ae: ArithmeticException => println(s"Result AE: $ae") } } }Result AE: java.lang.ArithmeticException: / by zero
Here we use the throw keyword to create an exception. With the case, we catch all Throwables—so all exceptions are caught here.
object Program { def main(args: Array[String]): Unit = { try { // Throw an Exception. throw new Exception("Failure") } catch { // Catch all Throwable exceptions. case _: Throwable => println("An exception was thrown") } } }An exception was thrown
NullPointerException
The NullPointerException
is common. It is caused when we try to access a field or method on a null
variable. Here we see a Scala stack trace.
object Program { def main(args: Array[String]): Unit = { // Print length of this string. var x = "cat" println(x.length) // Reassign string to null. // ... Now a NullPointerException is caused. x = null println(x.length) } }3 java.lang.NullPointerException: Cannot invoke "String.length()" because "x" is null at Program$.main(program.scala:12) at Program.main(program.scala)...
With the try, catch and throw keywords, we implement basic exception handling in Scala. With cases, we match specific kinds of Throwable exceptions, like ArithmeticException
.