Exceptions: The failwith Function (F#)

The failwith function generates an F# exception.

failwith error-message-string

Remarks

The error-message-string in the previous syntax is a literal string or a value of type string. It becomes the Message property of the exception.

The exception that is generated by failwith is a Microsoft.FSharp.Core.FailureException exception, which is a reference that has the name Failure in F# code. The following code illustrates the use of failwith to throw an exception.

let divideFailwith x y =
  if (y = 0) then failwith "Divisor cannot be zero." 
  else
    x / y

let testDivideFailwith x y =
  try
     divideFailwith x y
  with
     | Failure(msg) -> printfn "%s" msg; 0

let result1 = testDivideFailwith 100 0

See Also

Reference

Exception Types (F#)

Exceptions: The try...with Expression (F#)

Exceptions: The try...finally Expression (F#)

Exceptions: the raise Function (F#)

Other Resources

Exception Handling (F#)