2 people like it.

Raising arbitrary exceptions with failwith-style syntax

failwith/failwithf are a useful operators, but they only raise exceptions of type SystemException. Here's a simple way to generalize them.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
let gfailwith (exncons : string -> #exn) (msg : string) = exncons msg |> raise
let gfailwithf (exncons : string -> #exn) fmt = 
                    Printf.ksprintf (gfailwith exncons) fmt

// example

open System

let failwithf fmt = gfailwithf (fun msg -> new ArgumentException(msg)) fmt

let rec factorial =
    function
    | n when n < 0 -> failwithf "factorial: invalid argument %d." n 
    | 0 -> 1
    | n -> n * factorial (n-1)


factorial -2
val gfailwith : exncons:(string -> #exn) -> msg:string -> 'b

Full name: Script.gfailwith
val exncons : (string -> #exn)
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
type exn = System.Exception

Full name: Microsoft.FSharp.Core.exn
val msg : string
val raise : exn:System.Exception -> 'T

Full name: Microsoft.FSharp.Core.Operators.raise
val gfailwithf : exncons:(string -> #exn) -> fmt:Printf.StringFormat<'b,'c> -> 'b

Full name: Script.gfailwithf
val fmt : Printf.StringFormat<'b,'c>
module Printf

from Microsoft.FSharp.Core
val ksprintf : continutation:(string -> 'Result) -> format:Printf.StringFormat<'T,'Result> -> 'T

Full name: Microsoft.FSharp.Core.Printf.ksprintf
namespace System
val failwithf : fmt:Printf.StringFormat<'a,'b> -> 'a

Full name: Script.failwithf
val fmt : Printf.StringFormat<'a,'b>
Multiple items
type ArgumentException =
  inherit SystemException
  new : unit -> ArgumentException + 4 overloads
  member GetObjectData : info:SerializationInfo * context:StreamingContext -> unit
  member Message : string
  member ParamName : string

Full name: System.ArgumentException

--------------------
ArgumentException() : unit
ArgumentException(message: string) : unit
ArgumentException(message: string, innerException: exn) : unit
ArgumentException(message: string, paramName: string) : unit
ArgumentException(message: string, paramName: string, innerException: exn) : unit
val factorial : _arg1:int -> int

Full name: Script.factorial
val n : int

More information

Link:http://fssnip.net/do
Posted:11 years ago
Author:Eirik Tsarpalis
Tags: exceptions , failwith