X x;
try
{
x = exampleObject.DoSomething ();
}
catch (ThisCanGoWrongException ex)
If doSomething returns something, it can't meanwhile return an error, except there is enough room in the result Space. A well known instance of this phenomenon is a C-library, which reads a byte and returns an int. While bytes are considered unsigned, the error-case is/was a -1.
But now you have to do an ugly cast to do.
What do you do, if the result space does not give you room for results, meaning "invalid"? Well, you can use a Wrapper, which returns, instead of an T an Either[Error, T]. The right result usually means an result which is alright, and left is left to mean a kind of error.
Instead of the Error as special kind of value, the user of your library is - in statically typed languages - informed beforehand, that there is something which might go wrong.
In contrast, for
String ips = getIP ("programmers.se.com");
// returns "err.or.in.DNS" in errorcase - but programmer
// forgot to check
for (String b : ips.split (".")) {
Integer.parseInt (b); // crash here
Sometimes, methods get called for their side effect, and the return value isn't inspected at all. Then an error can slip through undetected.
user.setAge (-42);
Maybe the class returns a "false" or a message "Invalid age, must be >= 0". But many languages allow to ignore the returned result. An exception would be preferred here.
A problem with exceptions and wrapped result is, that they sometimes clutter the code, and make it harder to follow the healthy case. Maybe we will see improvements there in the future - Java is for example trying to simplify the handling of exceptions recently. IDEs could probably hide or fold exception code on demand.
In some cases, it might be reasonable to return a special Null object. Think about searching a special User in the Database. If something goes wrong, you could return null.
println (null.getName ()); // crash: NPE
An often seen solution is, to return a List with one Element in the normal case, and zero values in the defect case.
users = db.get ("Zappa");
for (User u : users) {
u.doSomething ();
This will work with one or none Element, and Languages like Haskell or Scala have a special purpose class for this, a Maybe or an Option.
Option is a parametrized class. An Option[T] is either a Some (T) or a None. The user still has to check the result, but can't forget it that easily.
This is similar to the result of an empty List, and might not be appropriate everywhere, but often it is.