Skip to content

Instantly share code, notes, and snippets.

@dtrenz
Last active February 3, 2016 21:17
Show Gist options
  • Save dtrenz/589dbb71af07433da20b to your computer and use it in GitHub Desktop.
Save dtrenz/589dbb71af07433da20b to your computer and use it in GitHub Desktop.
A Swift 2 error throwing example.
typealias CustomErrorType = protocol<ErrorType, CustomStringConvertible>
struct Example {
enum Error: CustomErrorType {
case ZombieApocalypse
case RobotOverlords
case Cthulhu
var description: String {
switch self {
case ZombieApocalypse:
return "Brains!!!!!!"
case RobotOverlords:
return "01110111 01100101 01101100 01100011 01101111 01101101 01100101"
case Cthulhu:
return "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn"
}
}
}
func methodThatThrows() throws {
// zombies!
throw Error.ZombieApocalypse
// robots!
throw Error.RobotOverlords
// lovecraft!
throw Error.Cthulhu
}
func foo() {
do {
try methodThatThrows()
} catch let error as Error {
print(error)
switch error {
case .ZombieApocalypse:
// handle a zombie apocalypse
case .RobotOverlords:
// handle robot overlords
case .Cthulhu:
// handle cthulhu (as if)
}
} catch {
// Unexpected error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment