F# exceptions
last modified December 2, 2026
In this article we raise and handle exceptions in F#.
An exception signals an error that interrupts the normal flow of a program. When an exception is raised, the running function stops, and the exception travels up through the calling functions until some code handles it. If nothing handles it, the program ends with an error report. F# uses the exceptions of .NET, so the same mechanism reports errors from F# code and from the .NET libraries.
An unhandled exception
Integer division by zero is a typical error that raises an exception.
let divide a b = a / b printfn "%d" (divide 10 3) printfn "%d" (divide 10 0) printfn "done"
The second call raises a DivideByZeroException. The program
stops, so done is never printed. The output shows the first
two lines of the report; the rest is a stack trace that lists the functions
the exception passed through.
λ dotnet fsi unhandled.fsx 3 System.DivideByZeroException: Attempted to divide by zero. at <StartupCode$FSI_0001>.$FSI_0001.main@() in unhandled.fsx:line 4
Handling an exception
The try...with expression runs the code after
try. If it raises an exception, the rules after
with are matched against the exception, as in a
match expression.
open System
let safeDivide a b =
try
a / b
with
| :? DivideByZeroException ->
printfn "cannot divide %d by zero" a
0
printfn "%d" (safeDivide 10 3)
printfn "%d" (safeDivide 10 0)
printfn "done"
safeDivide returns 0 when the divisor is zero.
| :? DivideByZeroException ->
The :? pattern tests the type of the exception. Like every F#
expression, try...with has a value: the value of the
try block, or the value of the matching handler. Both must have
the same type, here int.
λ dotnet fsi try_with.fsx 3 cannot divide 10 by zero 0 done
Matching exception types
One try block can raise different exceptions. Each rule
handles one type, and as binds the exception object to a name.
open System
let parse (text: string) =
try
let n = Int32.Parse text
$"parsed {n}"
with
| :? FormatException -> $"'{text}' is not a number"
| :? OverflowException -> $"'{text}' does not fit into an int"
| :? ArgumentNullException as e -> $"no input: {e.Message}"
for input in ["127"; "12a"; "99999999999"; null] do
printfn "%s" (parse input)
Int32.Parse raises a different exception for each kind of bad
input.
| :? ArgumentNullException as e -> $"no input: {e.Message}"
Every exception has a Message property with a description.
Exceptions that no rule matches are not caught and travel further up. The
.NET documentation lists the exceptions each method can raise.
λ dotnet fsi exception_types.fsx parsed 127 '12a' is not a number '99999999999' does not fit into an int no input: Value cannot be null. (Parameter 's')
Raising an exception with failwith
The failwith function raises a general exception with a
message. It is the quickest way to stop when something is wrong. The
Failure pattern catches such exceptions and extracts the
message.
let average (values: float list) =
if List.isEmpty values then failwith "average of an empty list"
List.sum values / float values.Length
let report values =
try
printfn "average: %.2f" (average values)
with
| Failure msg -> printfn "error: %s" msg
report [2.0; 4.5; 7.0]
report []
The if without else raises the exception for an
empty list; otherwise the function goes on to the next line.
failwith has a generic return type, so it fits wherever a value
is expected.
λ dotnet fsi failwith.fsx average: 4.50 error: average of an empty list
Argument and operation errors
.NET has specific exceptions for common errors. F# has functions that raise
them: invalidArg for a bad argument and invalidOp
for an operation that is not allowed in the current state. The
raise function raises any exception object.
open System
let percent part total =
if total <= 0 then invalidArg (nameof total) "must be positive"
if part < 0 || part > total then invalidArg (nameof part) $"{part} is out of range"
100 * part / total
let check part total =
try
printfn "%d%%" (percent part total)
with
| :? ArgumentException as e -> printfn "%s: %s" e.ParamName e.Message
check 3 4
check 5 0
check 7 4
let first (items: int list) =
if items.IsEmpty then raise (InvalidOperationException "the list is empty")
items.Head
try
printfn "%d" (first [8; 9])
printfn "%d" (first [])
with
| :? InvalidOperationException as e -> printfn "error: %s" e.Message
percent checks both arguments before it computes anything.
if total <= 0 then invalidArg (nameof total) "must be positive"
invalidArg takes the name of the parameter and a message and
raises an ArgumentException. The nameof operator
returns the name of a variable as a string, so a renamed parameter cannot
leave a stale name in the message.
if items.IsEmpty then raise (InvalidOperationException "the list is empty")
raise takes an exception object; here we create an
InvalidOperationException with a message. A
try...with also works at the top level of a script. The first
call prints 8, and the second one jumps to the handler.
λ dotnet fsi arguments.fsx 75% total: must be positive (Parameter 'total') part: 7 is out of range (Parameter 'part') 8 error: the list is empty
Custom exceptions
The exception keyword defines a new exception type. Like a
union case, it can carry data, and it is matched by its name.
exception InsufficientFunds of balance: decimal * requested: decimal
exception AccountLocked of string
type Account = { Owner: string; Balance: decimal; Locked: bool }
let withdraw amount account =
if account.Locked then raise (AccountLocked account.Owner)
if amount > account.Balance then raise (InsufficientFunds (account.Balance, amount))
{ account with Balance = account.Balance - amount }
let tryWithdraw amount account =
try
let updated = withdraw amount account
printfn "%s: new balance %M" account.Owner updated.Balance
with
| InsufficientFunds (balance, requested) ->
printfn "%s: cannot withdraw %M, balance is %M" account.Owner requested balance
| AccountLocked owner ->
printfn "account of %s is locked" owner
let anna = { Owner = "Anna"; Balance = 120m; Locked = false }
let peter = { Owner = "Peter"; Balance = 500m; Locked = true }
tryWithdraw 50m anna
tryWithdraw 200m anna
tryWithdraw 10m peter
We define two exceptions for a bank account.
exception InsufficientFunds of balance: decimal * requested: decimal
The exception carries the balance and the requested amount, so the handler can produce a precise message.
| InsufficientFunds (balance, requested) ->
Custom exceptions are matched without :?, with a pattern like
a union case.
λ dotnet fsi custom.fsx Anna: new balance 70 Anna: cannot withdraw 200, balance is 120 account of Peter is locked
Cleaning up with try...finally
The finally block runs when the try block ends,
whether it finishes normally or with an exception. It is meant for cleanup
that must always happen.
let runTask name work =
printfn "start %s" name
try
work ()
printfn "finished %s" name
finally
printfn "cleanup %s" name
runTask "task A" (fun () -> printfn "working")
try
runTask "task B" (fun () -> failwith "disk full")
with
| Failure msg -> printfn "task B failed: %s" msg
The work function is passed in as a parameter. Task B raises
an exception, so finished task B is never printed, but the
cleanup still runs before the exception reaches the outer handler. F# has
no single try...with...finally; the two forms are nested
instead.
λ dotnet fsi finally.fsx start task A working finished task A cleanup task A start task B cleanup task B task B failed: disk full
The use keyword
Objects that hold system resources, such as open files, implement the
IDisposable interface. Their Dispose method
releases the resource. A use binding calls it automatically
when the value goes out of scope, even after an exception; it replaces
an explicit try...finally.
open System.IO
let path = Path.Combine(Path.GetTempPath(), "notes.txt")
let writeNotes (lines: string list) =
use writer = new StreamWriter(path)
for line in lines do
if line = "" then invalidArg (nameof lines) "empty line"
writer.WriteLine line
writeNotes ["buy milk"; "call Lucia"]
printf "%s" (File.ReadAllText path)
try
writeNotes ["first"; ""; "third"]
with
| :? System.ArgumentException as e -> printfn "error: %s" e.Message
printfn "%A" (File.ReadAllLines path)
File.Delete path
We write lines to a temporary file and read them back.
use writer = new StreamWriter(path)
use works like let, but the writer is disposed at
the end of writeNotes. Disposing a StreamWriter
flushes its buffer and closes the file. The new keyword is
recommended when creating disposable objects.
printfn "%A" (File.ReadAllLines path)
The second call fails on the empty line. The file was still closed, and it contains the line written before the error.
λ dotnet fsi use_binding.fsx buy milk call Lucia error: empty line (Parameter 'lines') [|"first"|]
Rethrowing an exception
Sometimes a handler only records an error and lets it continue upwards.
The reraise function raises the caught exception again and
keeps its original stack trace. It can only be called in a
with block.
let loadSetting (settings: Map<string, string>) key =
try
settings[key]
with
| :? System.Collections.Generic.KeyNotFoundException ->
printfn "log: setting '%s' is missing" key
reraise ()
let settings = Map ["host", "localhost"; "port", "8080"]
try
printfn "host = %s" (loadSetting settings "host")
printfn "user = %s" (loadSetting settings "user")
with
| e -> printfn "startup failed: %s" (e.GetType().Name)
Indexing a map with a missing key raises a
KeyNotFoundException. The inner handler logs the problem and
rethrows it, and the outer handler decides what to do.
| e -> printfn "startup failed: %s" (e.GetType().Name)
A plain name pattern catches every exception. Catch-all handlers belong at the top of a program, where an error is reported; deep inside a program they hide bugs.
λ dotnet fsi reraise.fsx host = localhost log: setting 'user' is missing startup failed: KeyNotFoundException
Exceptions and Result
Exceptions suit unexpected failures, such as a missing file or a broken connection. Errors that are part of normal operation, such as invalid user input, are often better returned as values with the Result type. A small function converts one into the other at the boundary with .NET code.
open System
let tryCall f x =
try
Ok (f x)
with
| e -> Error e.Message
let parseDate (s: string) = DateOnly.ParseExact(s, "yyyy-MM-dd")
for s in ["2026-12-02"; "2026-13-01"; "yesterday"] do
match tryCall parseDate s with
| Ok d -> printfn "%s: %s" s (d.DayOfWeek.ToString())
| Error msg -> printfn "%s: %s" s msg
tryCall runs any one-argument function and turns its
exception into an Error with the message. The caller then
works with an ordinary value and the compiler makes it handle both cases.
λ dotnet fsi to_result.fsx 2026-12-02: Wednesday 2026-13-01: String '2026-13-01' was not recognized as a valid DateOnly. yesterday: String 'yesterday' was not recognized as a valid DateOnly.
Source
F# language reference: Exception Handling
F# language reference: Resource Management: The use Keyword
In this article we have handled exceptions with try...with,
raised them with failwith, invalidArg and
raise, defined custom exceptions, cleaned up with
try...finally and use, rethrown exceptions and
converted them to results. Errors as values are covered in
F# Result type, pattern matching in
F# match expression, and modules in
F# modules and namespaces.
Author
List all F# tutorials.