Error handling: return values and exceptions


Two approaches






Exceptions’ claimed virtues

Exceptions try to declutter code (



Exceptions try to address these possible shortcomings:


But it’s not all good





Good intentions: checked exceptions








The way forward














Further reading


The Necessity of Exceptions

Checked exceptions


Scala handling-Handling exceptions


Querying in Slick with many optional constraints

It’s a common use case to have to write queries with multiple constraints (ie where conditions) where each of these may or may not be present. For example, you could have an interface where the user may wish to filter according to different columns or criteria. In the old days this meant having to do very nasty sql generation by hand, by constructing some base query and then adding where clauses to it.

And even If you were not doing the sql by hand and using some kind of abstraction on top, the code would still require tedious and repetitive logic, polluting the code with if’s for each constraint that you may want to filter on.

One of the nice properties of Slick is how operations on queries are accumulated in the typical functional way. Queries are immutable, adding a constraint to a query returns another query that inherits all the operations done until then plus the new operation. This makes accumulation of constraints very readable, and makes queries composable and reusable. But how do we succinctly support the notion of accumulating optional operations?

Remember, this is Scala, this is the kind of thing we expect to be able to do concisely and elegantly, just like the Option type allows us to handle chaining of operations that may fail without having to write all those ugly if-else blocks. But unlike the case with Option, what we want to do is operate on a value that does exist, but where the operation itself is what is optional.

I’m convinced that there must be a well known functional pattern for this use case, but I don’t know what it is. Feel free to let me know in the coments, much appreciated. Anyhow, here’s what I came up with

// optionally filter on a column with a supplied predicate
case class MaybeFilter[X, Y](val query: scala.slick.lifted.Query[X, Y]) {
def filter[T](data: Option[T])(f: T => X => scala.slick.lifted.Column[Boolean]) = { => MaybeFilter(query.filter(f(v)))).getOrElse(this)

It looks more complicated than it is because of the type annotations to make it generic, but the mechanism is quite simple. If the optional constraint is present, return a new query with the filtering operation accumulated. Otherwise return the existing accumulated query unchanged.

And here’s how you use it, in this example there are five optional constraints

// example use case
def find(id: Option[Int], createdMin: Option[Date], createdMax: Option[Date], modifiedMin: Option[Date], modifiedMax: Option[Date]) = {

val query = MaybeFilter(Query(this))
.filter(id)(v => d => === v)
.filter(createdMin)(v => d => d.created >= v)
.filter(createdMax)(v => d => d.created <= v)
.filter(modifiedMin)(v => d => d.modified >= v)
.filter(modifiedMax)(v => d => d.modified <= v)



Where did the if‘s go!

Parallel collections for vote processing

At AgoraVoting we recently completed a very important feature, cryptographically secure voting. Among many other things, this adds a lot of heavy number crunching to the process of carrying out elections. One of the steps in the process validates votes, using something called proofs of knowledge. I won’t go into the math details here, just note that like other domains such as 3D graphics, processing votes is embarrassingly parallel. So we carried out an experiment to see how Scala’s parallel collections can achieve parallelism for one particular task.

In this experiment, we have to parse voting records which are then transformed into collections for their validation. The technique is to first obtain a collection with all the necessary data, and then compute in parallel on it. But first, lets see what happens with sequential code, for comparison. I’ve left out the preprocessing code that first obtains the collection, here’s the compute-intensive fragment:


ctexts.foreach( vote => {
vote.foreach( question => {

val pk_p = BigInt((question(2) \ "p").as[String])
val pk_g = BigInt((question(2) \ "g").as[String])

val commitment = BigInt((question(0) \ "commitment").as[String])
val response = BigInt((question(0) \ "response").as[String])
val challenge = BigInt((question(0) \ "challenge").as[String])
val alpha = BigInt((question(1) \ "alpha").as[String])

val toHash = alpha + "/" + commitment
val digest = MessageDigest.getInstance("SHA-256")
val hash = digest.digest(toHash.getBytes("UTF-8"))
val expected = BigInt(1, hash)

assert (challenge == expected)

val first_part = pk_g.modPow(response, pk_p)
val second_part = commitment * (alpha.modPow(challenge, pk_p)) % pk_p

assert(first_part == second_part)


Here’s what happens when running this code:


as you can see, the cores are underutilized. This test run took 1175.254 seconds. Now let’s turn ctexts into a parallel collection before processing on it:

[scala highlight=”1″]

ctexts.par.foreach( vote => {
vote.foreach( question => {

// the same code here …



Yes, that’s a difference of just three characters, par converts ctexts into a parallel collection. Here’s what happens:


All the cores are maxed out, total time: 307.184 seconds. Not bad!