F Sharp Programming/Exception Handling

When a program encounters a problem or enters an invalid state, it will often respond by throwing an exception. Left to its own devices, an uncaught exception will crash an application. Programmers write exception handling code to rescue an application from an invalid state.

It is, of course, wholly possible to catch multiple types of exceptions in a single with block. For example, according to the MSDN documentation, the System.Int32.Parse(s : string) method will throw three types of exceptions:

The code above demonstrates how to recover from an invalid state. However, when designing F# libraries, its often useful to throw exceptions to notify users that the program encountered some kind of invalid input. There are several standard functions for raising exceptions:

type'atree=|Nodeof'a*'atree*'atree|Emptyletrecaddx=function|Empty->Node(x,Empty,Empty)|Node(y,left,right)->ifx>ythenNode(y,left,addxright)elseifx<ythenNode(y,addxleft,right)elsefailwithf"Item '%A' has already been added to tree"x

Notice that our finally block executed in spite of the exception. Finally blocks are used most commonly to clean up resources, such as closing an open file handle or closing a database connection (even in the event of an exception, we do not want to leave file handles or database connections open):

openSystem.Data.SqlClientletexecuteScalarconnectionStringsql=letconn=newSqlConnection(connectionString)tryconn.Open()(* this line can throw an exception *)letcomm=newSqlCommand(sql,conn)comm.ExecuteScalar()(* this line can throw an exception *)finally(* finally block guarantees our SqlConnection is closed, even if our sql statement fails *)conn.Close()

Many objects in the .NET framework implement the System.IDisposable interface, which means the objects have a special method called Dispose to guarantee deterministic cleanup of unmanaged resources. It's considered a best practice to call Dispose on these types of objects as soon as they are no longer needed.

However, this can be occasionally bulky and cumbersome, especially when dealing with many objects which implement the IDisposable interface. F# provides the keyword use as syntactic sugar for the pattern above. An equivalent version of the code above can be written as follows: