Panic in Standard ML

exception Problem of string

fun main () =
  (* 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 Problem "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. *)
  (* 
  let
    val file = TextIO.openOut "/tmp/file"
  in
    TextIO.closeOut file
  end
  handle IO.Io {name, ...} => raise Problem name
  *)

val _ = main ()

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

The main function immediately raises an exception with the message “a problem”. This is equivalent to the panic in the original example.

The commented-out section shows how you might use exceptions to handle errors when working with files. In this case, if opening the file fails, an exception is raised with the error message.

To run this program, you would typically save it in a file with a .sml extension and then use an SML interpreter or compiler. For example, if you’re using Standard ML of New Jersey (SML/NJ):

$ sml panic.sml
uncaught exception Problem with "a problem"
  raised at: panic.sml:6.3-6.26

This output shows that an exception was raised with the message “a problem”, along with the file and line number where it occurred.

Note that unlike some languages which use exceptions for handling of many errors, in Standard ML it’s idiomatic to use option types or result types for expected error cases, reserving exceptions for truly exceptional situations.