What does this F# code look like in Erlang – Part 3 of N

Relat­ed Posts


Throw­ing Excep­tions

In F#, you can define a cus­tom excep­tion type by cre­at­ing a type that inher­it from System.Exception or using the light­weight excep­tion syn­tax to define them with the same syn­tax as dis­crim­i­nat­ed unions.

You can throw excep­tions in F# using the raise key­word or using fail­with or fail­withf:

excep­tion MyEx­cep­tionA

excep­tion MyEx­cep­tionB of string

let exThrow­er (isA : bool option) =

    match isA with

    | Some(true) -> raise MyEx­cep­tionA

    | Some(false) -> raise <| MyExceptionB(“Blah Blah”)

    | _ -> raise <| new System.Exception()

    | _ -> fail­with “Not a valid input”

Erlang also has a num­ber of dif­fer­ent excep­tion types, the most com­mon ways to raise an excep­tion in Erlang is via:

  • error(Reason) – ter­mi­nates the cur­rent process and includes a stack trace.
  • exit(Reason) – sim­i­lar to errors, but does not return the stack trace.
  • throw(Reason) – throws excep­tions that the caller can be expect­ed to han­dle, also used as a way to return from deep recur­sion.

1> throw(“Blah Blah”).

** excep­tion throw: “Blah Blah”

2> error(boo).

** excep­tion error: boo

3> exit(foo).

** excep­tion exit: foo


Catch­ing Excep­tions

In F#, you can imple­ment a try-catch block using the try-with key­words, and it’s real­ly easy to use pat­tern match­ing to make han­dling mul­ti­ple types of excep­tions real­ly easy.

Bor­row­ing from the won­der­ful­ly humor­ous exam­ple from Learn you some Erlang for great good! here’s how it’ll look in F#:


In Erlang, the syn­tax is sur­pris­ing­ly sim­i­lar:


Anoth­er thing to keep in mind is that whilst F# has try-with and try-final­ly blocks there is no equiv­a­lent of C#’s try-catch-final­ly block. In Erlang the try-catch-final­ly block looks like this:

black_knight(Attack) when is_function(Attack, 0) –>

    try Attack() of

        _ -> “None shall pass.”


        throw:slice   -> “It is but a scratch.”;

        error:cut_arm -> “I’ve had worse.”;

        exit: cut_leg -> “Come on you pan­sy!”;

        _:_             -> “Just a flesh wound.”


        io:format(“Attack finished…~n”, [])