Skip to content

Instantly share code, notes, and snippets.

@delba
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delba/a4dbc258ec94f0637c15 to your computer and use it in GitHub Desktop.
Save delba/a4dbc258ec94f0637c15 to your computer and use it in GitHub Desktop.
Typing the throwable errors
func catchAll(name: String?) {
do {
try throwSomething(name)
} catch {
print("An error occured")
}
}
func catchAllWithReference(name: String?) {
do {
try throwSomething(name)
} catch let error {
print("This error occured: \(error)")
}
}
func catchNameError(name: String?) {
do {
try throwSomething(name)
} catch is NameError {
print("A NameError occured")
} catch {
print("An Error occured")
}
}
func catchNameErrorWithReference(name: String?) {
do {
try throwSomething(name)
} catch let error where error is NameError {
print("A NameError occured: \(error)")
} catch {
print("An Error occured")
}
}
func catchNameErrorMessages(name: String?) {
do {
try throwSomething(name)
} catch let NameError.Nil(message) {
print(message)
} catch let NameError.Wrong(message) {
print(message)
} catch {
print("An Error occured")
}
}
enum NameError: ErrorType {
case Nil(String)
case Wrong(String)
init?(name: String?) {
switch name {
case .None:
self = .Nil("can't be nil")
case let .Some(name) where name == "damien":
self = .Wrong("can't be damien")
default:
return nil
}
}
}
func throwSomething(name: String?) throws {
if let error = NameError(name: name) {
throw error
}
}
let names: [String?] = [nil, "damien", "sophie"]
for name in names {
catchAll(name)
catchAllWithReference(name)
catchNameError(name)
catchNameErrorWithReference(name)
catchNameErrorMessages(name)
}
func throwSomething(name: String?) throws(NameError) {
if let error = NameError(name: name) {
throw error
}
}
do {
try throwSomething(nil)
} catch let .Nil(message) {
print(message)
} catch let .Wrong(message) {
print(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment