Skip to content

Instantly share code, notes, and snippets.

@ryantxr
Last active March 11, 2016 17:40
Show Gist options
  • Save ryantxr/90e404fe2416f053052e to your computer and use it in GitHub Desktop.
Save ryantxr/90e404fe2416f053052e to your computer and use it in GitHub Desktop.
Example swift exception throw and catch.
enum ArrayError : ErrorType{
case OutOfBounds
}
class SomeClass {
var test: NSArray! = ["Test1", "Test2"]
func testCode() {
do{
try testing(3)
} catch let error{
print("error = \(error)") // for index 3 this would print "error = OutOfBounds\n"
}
}
func testing(index: Int) throws -> String {
guard index < test.count else{
throw ArrayError.OutOfBounds
}
return test[index] as! String
}
}
let sC = SomeClass()
sC.testCode()
// Credit to: http://stackoverflow.com/users/1066899/the-critic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment