Skip to content

Instantly share code, notes, and snippets.

@rcoh
Last active June 15, 2020 21:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcoh/11387402 to your computer and use it in GitHub Desktop.
Save rcoh/11387402 to your computer and use it in GitHub Desktop.
Safely Catch Throwable
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