Particularly Vexing Exceptions

If you’re a developer and you’ve been around the internet for a while, you may have read Eric Lippert’s Vexing Exceptions. If you haven’t, you should go do that, it’s a good read.

Back? Ok then. In the article, the author talks about a situation with C#’s Int32.Parse method. Apparently in C#, the method to parse a string to an int throws an exception upon failure. Because this was so ‘vexing’, the language team later implemented Int32.TryParse that returns a boolean upon success or failure, and has an out parameter to return the actual parsed int.

Personally, given those two options, I prefer the original parse function that can throw. I don’t like out parameters, and checking the boolean is just as irritating as catching a parse exception. However, C# is a language without the Maybe monad.

Unfortunately for us, Haskell’s read function also throws an exception instead of returning Maybe a. Unlike the C# example, this is actually vexing because in Haskell, you can only catch exceptions in the IO monad. So what to do?

After some searching online, I found the answer. There is a function in Text.Read:

readMaybe :: Read a => String -> Maybe a

As it’s name would imply, readMaybe attempts to parse a string into some other type, and wraps it in a Just upon success, or returning Nothing.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: