posts - 280, comments - 318, trackbacks - 0

My Links

News

View Steve Michelotti's profile on LinkedIn

Twitter












Tag Cloud

Archives

Post Categories

Blend Bloggers

Bloggers that I follow

Books

F# Bloggers

F# Communities

F# Online Books

Fonts

HTML CSS ASP

Machine Learning

My Links

My Local UserGroups

My Online Presence

MY SA Links

Online Seminars

SA Software Companies

Web Design

No Thank You – Yours Truly – F#

I am plodding along with my F# book. I have reached the part where I know enough about the syntax of the language to understand something if I read it – but not enough about the language to be productive and write something useful. A bit of a frustrating place to be.

Needless to say when you are in this state of mind – you end up paging mindlessly through chapters of my F# book with no real incentive to learn anything until you hit “Exceptions”.

Raising an exception explicitly

So lets look at raising an exception explicitly – in C# we would throw the exception, F# is a lot more polite instead of throwing the exception it raises it, …

(raise (System.InvalidOperationException("no thank you")))

quite simple…

Catching an Exception

So I would expect to be able to catch an exception as well – lets look at some C# code first…

try
{
    Console.WriteLine("Raise Exception");
    throw new InvalidOperationException("no thank you");
}
catch
{
    Console.WriteLine("Catch Exception and Carry on..");
}                    
Console.WriteLine("Carry on...");
Console.ReadLine();

 

The F# equivalent would go as follows…

open System;
try
    Console.WriteLine("Raise Exception")
    raise (System.InvalidOperationException("no thank you"))
with
    | _ -> Console.WriteLine("Catch Exception and Carry on..")

Console.WriteLine("Carry on...")
Console.ReadLine();

 

In F# there is a “try, with” and a “try finally

Finally…

In F# there is a finally block however the “with” and “finally” can’t be combined.

open System;
try
    Console.WriteLine("Raise Exception")
    raise (System.InvalidOperationException("no thank you"))
finally    
    Console.WriteLine("Finally carry on...")
    Console.ReadLine()

Print | posted on Friday, April 09, 2010 5:52 PM | Filed Under [ F# ]

Feedback

Gravatar

# re: No Thank You – Yours Truly – F#

One of the best parts of F# is that exceptions are so infrequently necessary. Why use an exception when you can use a discriminated union?
4/12/2010 10:45 PM | Rick Minerich
Gravatar

# re: No Thank You – Yours Truly – F#

Rick - I have never heard of those till now - googled it and yeah - discriminated unions look really cool! I'm gona have to read more up on them! Thanks Mate!
4/13/2010 6:41 AM | Mark
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: