Home
Map
Exception HandlingHandle exceptions with try, catch and throw. Use case to match exception types.
Scala
This page was last reviewed on Dec 15, 2023.
Exceptions. 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.
An example. 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
Throw, Throwable. Here we use the throw keyword to create an exception. With the case, we catch all Throwables—so all exceptions are caught here.
Tip In Scala we must specify the Throwable type for the case to avoid a compiler warning.
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
Null, 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 15, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.