2

How do I help the F# compiler interpret re-throwing an exception as having no return value?

For example, consider wrapping an operation to log the exception:

let doDivision() =
    try
        2 / 0
    with ex ->
        log ex
        reraise

The compiler reports this error for reraise:

This expression was expected to have type int but here has type unit -> 'a

Edward Brey
  • 40,302
  • 20
  • 199
  • 253
  • It can't have "no return value", because then the `try` and `with` branches would have different types. It needs to have the same return type as the `try` branch, namely `int`. This is what the compiler tells you by "_this expression was expected to have type int_". – Fyodor Soikin Feb 21 '17 at 20:32
  • If I understand it correctly, reraise returns `'T`, which becomes `int` to match the `try` expression. – Edward Brey Feb 21 '17 at 20:35
  • Exactly........ – Fyodor Soikin Feb 21 '17 at 20:55
  • `unit -> 'a` is the type of a function, that takes no argument (unit, `()`). With this, you can easily guess that you forgot to call the function. Return value is `'a`, aka anything, which is exactly what you want. – Laurent Feb 21 '17 at 21:53

1 Answers1

7

"reraise" is a function. You need to pass unit to it.

let doDivision() =
    try
        2 / 0
    with ex ->
        log ex
        reraise ()
Foole
  • 4,754
  • 1
  • 26
  • 23