Panic in Scala
Our first example demonstrates how to handle unexpected errors in Scala. This is similar to the concept of panic in some other languages.
Running this program will cause it to throw an exception, print an error message and stack trace, and exit with a non-zero status.
When the first exception in main
is thrown, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first exception.
Note that unlike some languages which use exceptions for handling of many errors, in Scala it is idiomatic to use Try
, Option
, or Either
for error handling wherever possible. Throwing exceptions is typically reserved for truly exceptional situations that should halt program execution.
In Scala, we often use Try
to wrap operations that might throw exceptions. This allows us to handle potential errors in a more functional and composable way. The match
statement in our example demonstrates how to handle both successful and failed outcomes when using Try
.