Exceptions: the raise Function (F#)
The raise function is used to indicate that an error or exceptional condition has occurred. Information about the error is captured in an exception object.
raise (expression)
Remarks
The raise function generates an exception object and initiates a stack unwinding process. The stack unwinding process is managed by the common language runtime (CLR), so the behavior of this process is the same as it is in any other .NET language. The stack unwinding process is a search for an exception handler that matches the generated exception. The search starts in the current try...with expression, if there is one. Each pattern in the with block is checked, in order. When a matching exception handler is found, the exception is considered handled; otherwise, the stack is unwound and with blocks up the call chain are checked until a matching handler is found. Any finally blocks that are encountered in the call chain are also executed in sequence as the stack unwinds.
The raise function is the equivalent of throw in C# or C++. Use reraise in a catch handler to propagate the same exception up the call chain.
The following code examples illustrate the use of the raise function to generate an exception.
exception InnerError of string
exception OuterError of string
let function1 x y =
try
try
if x = y then raise (InnerError("inner"))
else raise (OuterError("outer"))
with
| InnerError(str) -> printfn "Error1 %s" str
finally
printfn "Always print this."
let function2 x y =
try
function1 x y
with
| OuterError(str) -> printfn "Error2 %s" str
function2 100 100
function2 100 10
The raise function can also be used to raise .NET exceptions, as shown in the following example.
let divide x y =
if (y = 0) then raise (System.ArgumentException("Divisor cannot be zero!"))
else
x / y
See Also
Reference
Exceptions: The try...with Expression (F#)
Exceptions: The try...finally Expression (F#)
Exceptions: The failwith Function (F#)
Exceptions: The invalidArg Function (F#)