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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 15, 2023 (edit).