Jowanza Joseph

View Original

The Beauty Of Error Handling In Scala

I’ve been writing Scala professionally for a handful months now, and I’ve come to really enjoy it’s unique language offerings when compared to my other heavily used programming languages. Wether it’s the type system of the pattern matching, Scala has great tools for the typical flow in a program. This is also the case with error handling. I’ve taken a few notes on how I handle errors in Scala and wanted to share those.

Try-Catch

Try-Catch is the OG of error handling, but it’s the sensible thing to do often times. It works in Scala the way it works in most other programming languages.

Try

Try was introduced in Scala 2.10, it allows a more functional approach to the failure-success handler. It allows for mapping on the success call and a graceful failure case. Here’s an example:

Option & Get Or Else

The semantics of the option class are interesting and I won’t butcher it. The best explanation I’ve seen is this one. I like to think of it as the following: I have a class that has a name and the age is optional. The optional type gets Some value (a string in this example) or nothing None. Here’s what it looks like it practice.

Either

Either is kind of a beast in Scala. It covers some similar semantics as Try, but has this concept of Left and Right. Traditionally, Left is seen as the negative case and Right as the positive. I use pattern matching to simplify following the flow:

Creating Custom Errors

There are a handful of exceptions you can throw in Scala. If throw a generic exception, you’ll throw a java.lang exception. Other exceptions are available to you by default. In the examples above I created custom errors by extending the generic exception class. Mixing in those exceptions when throwing errors is helpful (at least I found it to be).

Cheers.