Created
July 24, 2016 13:53
-
-
Save JoolsF/168a39cf466f5b8219a76b1a7f343494 to your computer and use it in GitHub Desktop.
Exception handling with Either 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.control.Exception._ | |
val r = new java.util.Random | |
def randomBoolean(exceptionChance: Int) = r.nextInt(exceptionChance) == 0 | |
def handling[Ex <: Throwable, T](exType: Class[Ex])(block: => T): Either[Ex, T] = | |
catching(exType).either(block).asInstanceOf[Either[Ex, T]] | |
def exceptionOrString = if(randomBoolean(4)) throw new RuntimeException("This is a runtime exception") else "Phew! You got a string" | |
val handleExample: Either[RuntimeException, String] = handling(classOf[RuntimeException])(exceptionOrString) | |
handleExample match { | |
case Left(exception) => println(exception) | |
case Right(string) => println(string) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment