reconciling functional programming and exceptions
TRANSCRIPT
@
~30 Italians @ Dublin Office
Weekly Scala MeetingsDeveloping in Scala for > 5 years
Active in local and international Scala Community
I’m a method which returns an Int.
@throws[FileNotFoundException]def someMethod: Int
Unless I hit an exception. Then I return nothing.
A) Wrap existing exceptions using the Scala Try type.
B) Return Error Types instead of throwing Exceptions.
The Solution
Try[T]
Failure[T] Success[T]
I return a container holding either the result type or the
exception.
def trySomeMethod: Try[Int]
Avoid Using foreach
foreach[U](f: (T) ⇒ U): UnitApplies the given function f if this is a Success, otherwise returns Unit if this is a Failure.
Alternatives
def someMethod : Either[IllegalArgumentException,Int]
def someApi: \/[ParseException,String]
Def someApi: Or[String, ParseException]
def trySomeMethod: Try[Int]
try catch scala.util.Try Either Scalatic Or Scalaz.\/
Guaranteed Return Type ✘ ✔ ✔ ✔ ✔Return Type Shows Potential Error
✘ ✔ ✔ ✔ ✔
Return Custom Error Objects Which Aren’t Exceptions
✘ ✘ ✔ ✔ ✔
Supports map, flatmap and for comprehensions.
✘ ✔ ✘ ✔ ✔
Api Specifies The Type of Exception Returned
✔ ✘ ✔ ✔ ✔
Provides Convenience Method For Wrapping Exception Throwing Code
N/A ✔ ✘ ✘ ✘
Call the supplied handler in the API code where you would normally escalate the Exception.
Exception used to be thrown here.
Then in your client code tell the APIs what handler to use by defining it in the context as an implicit.
Final Thoughts
Use a return type like Scalatic Or in favor of throwing exceptions in Scala code.
When exceptions are thrown by external API’s contain them in the imperative shell using scala.util.Try
Be considerate of logging once you lose the catch blocks.
Decouple reporting and recovery concerns – in your mind if not in the code.
Referenceshttp://danielwestheide.com/blog/2012/12/26/the-neophytes-guide-to-scala-part-6-error-handling-with-try.html
http://mauricio.github.io/2014/02/17/scala-either-try-and-the-m-word.html
http://www.scala-lang.org/api/current/index.html#scala.util.Try
http://www.slideshare.net/InfoQ/purely-functional-io
Bloch, J. (2008). Effective java. Pearson Education India.
http://twitter.github.io/effectivescala/#Error handling
https://www.parleys.com/tutorial/options-futures-how-unsuck-them
http://mavilein.github.io/scala/2015/09/01/comparing-error-handling-scalas-try-with-scalazs-either-disjunction/
http://typelevel.org/blog/2014/02/21/error-handling.html
https://docs.oracle.com/javase/tutorial/essential/exceptions/advantages.html
https://www.destroyallsoftware.com/talks/boundaries
http://typelevel.org/blog/2014/02/21/error-handling.html