Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I wonder what are the advantages of Maybe monad over exceptions? It looks like Maybe is just explicit (and rather space-consuming) way of try..catch syntax.

update Please note that I'm intentionally not mentioning Haskell.

share|improve this question
add comment

6 Answers

up vote 20 down vote accepted

Using Maybe (or its cousin Either which works basically the same way but lets you return an arbitrary value in place of Nothing) serves a slightly different purpose than exceptions. In Java terms, it's like having a checked exception rather than a runtime exception. It represents something expected which you have to deal with, rather than an error you did not expect.

So a function like indexOf would return a Maybe value because you expect the possibility that the item is not in the list. This is much like returning null from a function, except in a type-safe way which forces you to deal with the null case. Either works the same way except that you can return information associated with the error case, so it's actually more similar to an exception than Maybe.

So what are the advantages of the Maybe/Either approach? For one, it's a first-class citizen of the language. Let's compare a function using Either to one throwing an exception. For the exception case, your only real recourse is a try...catch statement. For the Either function, you could use existing combinators to make the flow control clearer. Here are a couple of examples:

First, let's say you want to try several functions that could error out in a row until you get one that doesn't. If you don't get any without errors, you want to return a special error message. This is actually a very useful pattern but would be a horrible pain using try...catch. Happily, since Either is just a normal value, you can use existing functions to make the code much clearer:

firstThing <|> secondThing <|> throwError (SomeError "error message")

Another example is having an optional function. Let's say you have several functions to run, including one that tries to optimize a query. If this fails, you want everything else to run anyhow. You could write code something like:

do a <- getA
   b <- getB
   optional (optimize query)
   execute query a b

Both of these cases are clearer and shorter than using try..catch, and, more importantly, more semantic. Using a function like <|> or optional makes your intentions much clearer than using try...catch to always handle exceptions.

Also note that you do not have to litter your code with lines like if a == Nothing then Nothing else ...! The whole point of treating Maybe and Either as a monad is to avoid this. You can encode the propagation semantics into the bind function so you get the null/error checks for free. The only time you have to check explicitly is if you want to return something other than Nothing given a Nothing, and even then it's easy: there are a bunch of standard library functions to make that code nicer.

Finally, another advantage is that a Maybe/Either type is just simpler. There is no need to extend the language with additional keywords or control structures--everything is just a library. Since they're just normal values, it makes the type system simpler--in Java, you have to differentiate between types (e.g. the return type) and effects (e.g. throws statements) where you wouldn't using Maybe. They also behave just like any other user-defined type--there is no need to have special error-handling code baked into the language.

Another win is that Maybe/Either are functors and monads, which means they can take advantage of the existing monad control flow functions (of which there is a fair number) and, in general, play nicely along with other monads.

That said, there are some caveats. For one, neither Maybe nor Either replace unchecked exceptions. You'll want some other way to handle things like dividing by 0 simply because it would be a pain to have every single division return a Maybe value.

Another problem is having multiple types of errors return (this only applies to Either). With exceptions, you can throw any different types of exceptions in the same function. with Either, you only get one type. This can be overcome with sub-typing or an ADT containing all the different types of errors as constructors (this second approach is what is usually used in Haskell).

Still, over all, I prefer the Maybe/Either approach because I find it simpler and more flexible.

share|improve this answer
add comment
  1. An exception can carry more information about the source of a problem. OpenFile() can throw FileNotFound or NoPermission or TooManyDescriptors etc. A None does not carry this information.
  2. Exceptions can be used in contexts that lack return values (e.g. with constructors in languages that have them).
  3. An exception allows you to very easily send the information up the stack, without a lot of if None return None-style statements.
  4. Exception handling almost always carries higher performance impact than just returning a value.
  5. Most importantly of all, an exception and a Maybe monad have different purposes - an exception is used to signify a problem, while a Maybe isn't.

    "Nurse, if there's a patient in room 5, can you ask him to wait?"

    • Maybe monad: "Doctor, there is no patient in room 5."
    • Exception: "Doctor, there is no room 5!"

    (notice the "if" - this means the doctor is expecting a Maybe monad)

share|improve this answer
4  
I don’t agree with points 2 and 3. In particular, 2 does not actually pose a problem in languages that use monads because those languages have conventions that do not generate the conundrum of having to handle failure during construction. Concerning 3, languages with monads have appropriate syntax for handling monads in a transparent way that does not require explicit checking (for instance, None values can just be propagated). Your point 5 is only kind of right … the question is: which situations are unambiguously exceptional? As it turns out … not many. –  Konrad Rudolph May 30 '12 at 14:28
1  
@KonradRudolph regarding (2), some languages with the Maybe monad (e.g. Scala) do have constructors and other contexts in which a return value is otherwise not possible or not useful. Regarding (3) - None values can only be propagated if you don't want to actually use the value. If you do, you have to test them. And if you do test them, you find out None and you don't know how to deal with it, what do you do? Propagation makes the most sense. This is the scenario I'm trying to describe that exceptions can make much easier. I accept that it does not always apply. –  Oak May 30 '12 at 14:35
1  
Regarding (2), you can write bind in such a way that testing for None doesn’t incur a syntactic overhead however. A very simple example, C# just overloads the Nullable operators appropriately. No checking for None necessary, even when using the type. Of course the check is still done (it’s type safe), but behind the scenes and doesn’t clutter your code. The same applies in some sense to your objection to my objection to (5) but I agree that it may not always apply. –  Konrad Rudolph May 30 '12 at 14:54
1  
+1 for point 5! I find that often exceptions are used when in fact it would be more appropriate to use the Maybe monad (or some other way of representing an optional type). The None return value is a valid return value indicating that a piece of code was executed without errors and found no valid result. An exception indicates that a piece of code encountered some error during execution. I think there is a different and it is important to make this distinction in code. –  Giorgio May 30 '12 at 18:19
1  
@Oak: Regarding (3), the whole point of treating Maybe as a monad is to make the propagating None implicit. This means that if you want to return None given None, you do not have to write any special code at all. The only time you need to match is if you want to do something special on None. You never need if None then None sort of statements. –  Tikhon Jelvis May 30 '12 at 20:23
show 4 more comments

"Maybe" is not a replacement for exceptions. Exceptions are meant to be used in exceptional cases (for instance: opening a db connection and the db server is not there although it should be). "Maybe" is for modeling a situation when you may or may not have a valid value; say you are getting a value from a dictionary for a key: it may be there or may be not - there is nothing "exceptional" about any of these outcomes.

share|improve this answer
    
Actually, I have quite a bit of code involving dictionaries where a missing key means stuff has gone horribly wrong at some point, most likely a bug in my code or in the code that converted the input into whatever is used at that point. –  delnan May 30 '12 at 15:17
3  
@delnan: I am not saying a missing value can't ever be a sign of an exceptional state - it just doesn't have to be. Maybe really models a situation where a variable may or may not have a valid value - think nullable types in C#. –  Nemanja Trifunovic May 30 '12 at 15:30
add comment

The Haskell type system will require the user to acknowledge the possibility of a Nothing, whereas programming languages often don't require that an exception be caught. That means that we'll know, at compile-time, that the user has checked for an error.

share|improve this answer
1  
There are checked exceptions in Java. And people often treated even them badly. –  Vladimir May 30 '12 at 13:31
1  
@DairT'arg ButJava requires checks for IO errors (as an example), but not for NPEs. In Haskell it's the other way around: The null equivalent (Maybe) is checked but IO errors simply throw (unchecked) exceptions. I'm unsure how much of a difference that makes, but I don't hear Haskellers complaining about Maybe and I think a lot of people would like NPEs to be checked. –  delnan May 30 '12 at 13:40
1  
@delnan People want NPE to be checked? They must be mad. And I mean that. Making NPE checked only makes sense if you have a way of avoiding it in the first place (by having non-nullable references, which Java doesn’t have). –  Konrad Rudolph May 30 '12 at 13:45
3  
@KonradRudolph Yes, people probably don't want it to be checked in the sense that they'll have to add a throws NPE to every single signature and catch(...) {throw ...} to every single method body. But I do believe there's a market for checked in a same sense as with Maybe: nullability is optional and tracked in the type system. –  delnan May 30 '12 at 13:49
    
@delnan Ah, then I agree. –  Konrad Rudolph May 30 '12 at 14:22
show 4 more comments

Exception handling can be a real pain for factoring and testing. I know python provides nice "with" syntax that allows you to trap exceptions without the rigid "try ... catch" block. But in Java, for example, try catch blocks are big, boilerplate, either verbose or extremely verbose, and hard to break up. On top of that, Java adds all the noise around checked vs. unchecked exceptions.

If, instead, your monad catches exceptions and treats them as a property of the monadic space (instead of some processing anomaly), then you're free to mix and match functions you bind into that space regardless of what they throw or catch.

If, better yet, your monad prevents conditions where exceptions could happen (like pushing a null check into Maybe), then even better. if...then is much, much easier to factor and test than try...catch.

From what I've seen Go is taking a similar approach by specifying that each function returns (answer, error). That's sort of the same as "lifting" the function into a monad space where the core answer type is decorated with an error indication, and effectively side-stepping throwing & catching exceptions.

share|improve this answer
add comment

The maybe monad is basically the same as most mainstream language's use of "null means error" checking (except it requires the null to be checked), and has largely the same advantages and disadvantages.

share|improve this answer
6  
Well, it does not have the same disadvantages since it can be statically type checked when used correctly. There is no equivalent of a null pointer exception when using maybe monads (again, assuming they are used correctly). –  Konrad Rudolph May 30 '12 at 13:44
    
Indeed. How do you think that should be clarified? –  Telastyn May 30 '12 at 13:58
    
@Konrad That's because in order to use the value (possibly) in the Maybe, you must check for None (though of course there's the ability to automate a lot of that checking). Other languages keep that sort of thing manual (mostly for philosophical reasons I believe). –  Donal Fellows May 30 '12 at 14:52
2  
@Donal Yes but note that most languages which implement monads do provide appropriate syntactic sugar so that this check can often be hidden away completely. E.g. you can just add two Maybe numbers by writing a + b without the need to check for None, and the result is once again an optional value. –  Konrad Rudolph May 30 '12 at 14:57
2  
The comparison with nullable types holds true for the Maybe type, but using Maybe as a monad adds syntax sugar that allows expressing null-ish logic a lot more elegantly. –  tdammers May 30 '12 at 16:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.