Last active
June 15, 2020 21:32
-
-
Save rcoh/11387402 to your computer and use it in GitHub Desktop.
Safely Catch Throwable
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
def safely[T](handler: PartialFunction[Throwable, T]): PartialFunction[Throwable, T] = { | |
case ex: ControlThrowable => throw ex | |
// case ex: OutOfMemoryError (Assorted other nasty exceptions you don't want to catch) | |
//If it's an exception they handle, pass it on | |
case ex: Throwable if handler.isDefinedAt(ex) => handler(ex) | |
// If they didn't handle it, rethrow. This line isn't necessary, just for clarity | |
case ex: Throwable => throw ex | |
} | |
// Usage: | |
/* | |
def doSomething: Unit = { | |
try { | |
somethingDangerous | |
} catch safely { | |
ex: Throwable => println("AHHH") | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment