F # - Why can not I declare a name within the 'try with' block?

4

The code works if you call a function or assign a value within the try-catch block:

module public test 

open System

let testing = 

  let divide = fun a b -> a / b

  try
    divide 100 0
  with
    | :? System.DivideByZeroException as ex -> printfn "Exception! %s (ex.Message); None.Value

or

module public test 

open System

let testing = 

  let divide = fun a b -> a / b

  let mutable num = divide 100 10

  try
    num = divide 100 0
  with
    | :? System.DivideByZeroException as ex -> printfn "Exception! %s (ex.Message); None.Value

When declaring a name inside the block, it does not leave me:

module public test 

open System

let testing = 
/*
El bloque que sigue a este objeto 'let' está sin finalizar. Cada bloque de 
código es una expresión y debe tener un resultado. 'let' no puede ser el 
elemento de código final en un bloque. Considere la posibilidad de asignar a 
este bloque un resultado explícito.
*/
  let divide = fun a b -> a / b

  try
    let num = 100
    let num2 = 20
    divide num num2
  with
    | :? System.DivideByZeroException as ex -> printfn "Exception! %s (ex.Message); None.Value
    
asked by Deiby Olaya Orejuela 05.05.2018 в 17:54
source

1 answer

1

This is because within the try-catch blocks it is not possible to declare variables. This is so to prevent them from declaring new variables because an error has been thrown somewhere in the block try , which would lead to the execution of the block catch without declaring the other variables. Therefore, you must declare the variables outside the try-catch blocks and you can assign them values within the try-catch block.

  

Therefore the first two codes that you include in your question are possible.

     

In order for the third party to be valid, you must declare the variables outside the block try in the following way:

module public test 

open System

let testing = 
/*
El bloque que sigue a este objeto 'let' está sin finalizar. Cada bloque de 
código es una expresión y debe tener un resultado. 'let' no puede ser el 
elemento de código final en un bloque. Considere la posibilidad de asignar a 
este bloque un resultado explícito.
*/

    let divide = fun a b -> a / b
    let num = 0
    let num2 = 0

    try
        num = 100
      num2 = 20
        divide num num2
    with
        | :? System.DivideByZeroException as ex -> printfn "Exception! %s (ex.Message); None.Value

This way, your problem should be solved.

    
answered by 05.05.2018 / 21:06
source