Panic in F#

open System
open System.IO

[<EntryPoint>]
let main argv =
    // We'll use exceptions throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to raise an exception.
    raise (Exception("a problem"))

    // A common use of exceptions is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // raising an exception if we get an unexpected error when creating a new file.
    try
        use file = File.Create("/tmp/file")
        0 // Return 0 for success
    with
    | ex -> 
        raise ex

In F#, we use exceptions to handle unexpected errors, which is similar to the concept of panic in some other languages. This program demonstrates how to raise exceptions and handle potential errors.

Running this program will cause it to raise an exception, print an error message and stack trace, and exit with a non-zero status.

When the first exception in main is raised, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first raise statement.

$ dotnet run
Unhandled exception. System.Exception: a problem
   at Program.main(String[] argv) in /path/to/Program.fs:line 7

Note that unlike some languages which use exceptions for handling of many errors, in F# (and functional programming in general) it is idiomatic to use Result types or Option types for error handling wherever possible, reserving exceptions for truly exceptional circumstances.

F# provides a robust type system and pattern matching capabilities that make working with Result and Option types very convenient for error handling. However, when interoperating with .NET libraries or in truly exceptional cases, exceptions are still used.