Reputation: 1805
Follow Code F#:
try
let result = 100/0
with
| :? Exception as ex -> printfn ex.Message
I get an error:
The block after 'let' is unfinished. Each block of code is an expression and must have a result. 'let' can not be the final code element in a block. Consider giving this block an explicit result.
What am I doing wrong ?
Upvotes: 1
Views: 459
Reputation: 5004
The issue is that let
by itself is not an expression:
In F# everything is an expression of a certain type. But let
alone is not an expression, is a binding and it has to be continued with some expression that, presumably, uses the value bound to the id result
.
Since you are merely testing the try/catch functionality. I assume you are not really interested in producing any values, that is why I added the expression: ()
after the let
.
try
let result = 100/0
()
with
ex -> printfn "%s" ex.Message
The try/with
expression requires that both sides return the same type of value, just like if/then/else
does. Since in the with
side printfn
returns unit
, I made the try
side also return a unit
value which is ()
. Think of it as the equivalent to void
in C#.
Upvotes: 8
Reputation: 24178
I can recommend different approach. This won't leave the result
variable undefined.
let result =
try
Some(100/0)
with
| :? Exception as ex -> printfn "%s" ex.Message; None
Upvotes: 2