As a commenter pointed out, Java has unchecked exceptions, so runtime errors do occur. Elm also has unchecked exceptions, for things like division by zero, but gets rid of the ones most commonly seen in practice. And as Chad's answer mentions, Elm's Maybe
/Result
types work quite differently in practice than Java's checked exceptions. An experienced Elm programmer would not write a function like toIntOrZero
(and if they did, they would probably not use case ... of
, preferring instead something like toIntOrZero = String.toInt >> Result.withDefault 0
).
Chaining multiple operations together with Result.map
, Result.andThen
, and so on gives a very expressive way of handling error cases without forcing the programmer to get too deep in the weeds. For example, if we want to write a function that validates an ID by converting it to an Int, looking it up in some data structure (when it might not be there), and then verifying some property associated with that user, we can write something like this:
lookupUser : Int -> Result String User
lookupUser intId = ...
userInGoodStanding : User -> Bool
userInGoodStanding user = ...
isValidId : String -> Bool
isValidId id =
String.toInt id
|> Result.andThen lookupUser
|> Result.map userInGoodStanding
|> Result.withDefault False
This reads, "convert the ID to an int, then look up the associated user, then verify the user, and if anything failed, return False." Your mileage may vary, but once you get to used to it, I (and many Elm programmers, I think!) find this to be a really nice way of writing code robust to errors.