Runtime exceptions in Elm

Today was the first Elmsinki meetup, where we gathered to discuss Elm the programming language. Ossi gave us a quick introduction to Elm. One of the points in his Elm elevator pitch was that there are no runtime exceptions. I asked what this means, but ultimately misunderstood the explanation. After thinking it through, here’s my current understanding:

Elm does not have an exception system. There’s no mechanism for throwing and catching exceptions. You might be able to build one, though.

You can have runtime errors in Elm. For example, there’s Debug.crash : String -> a, which is equivalent to Haskell’s error :: String -> a. They both abort the computation - there’s no way to handle the error. You can use this to define partial functions:

unsafeHead x =
  case x of
    (y :: _) -> y
    _ -> Debug.crash "oh no :("

There are also some other ways to get a runtime error, like running out of stack:

> g x = 0 + g x
<function> : a -> number
> g 0
RangeError: Maximum call stack size exceeded

You won’t have pattern matching errors in Elm. You have to always handle all the cases. We might try to define unsafeHead like this:

unsafeHead (x :: _) = x

The Elm compiler does not accept this and prints an error message:

This pattern does not cover all possible inputs.

6│ unsafeHead (x :: _) = x
You need to account for the following values:


When I heard “no runtime exceptions”, I first thought of total languages. Elm clearly isn’t one. I guess “no runtime exceptions” means “runtime exceptions/errors are rare”. Fair enough.

Comments or questions? Tweet to me or send me an e-mail.