1

I am currently writing a Swift 2 application that could throw an error. To prevent it from crashing my code, I am using do-try-catch.

In python we can do something like this:

try:
    functionThatThrowsError()
except exceptionOne:
    pass # exceptionOne was caught 
except exceptionTwo:
    pass # exceptionTwo was caught
else:
    pass # No Errors in code

I currently have this code in Swift:

do
{
    try functionThatThrowsError
} catch exceptionOne {
    //Do stuff
} catch exceptionTwo {
    //Do Stuff
}

How would I do this in Swift 2?

Edit: The 'posible duplicate' is not a duplicate of Swift do-try-catch syntax since the do-try-except does not check if the code executed successfully.

What I want to do is this:

Run a function that could throw an error
Check for one type of error
    Do code if the error happened
Check for another error type that occurred
    Do code if that error happened
If the function does not throw an error
    Do this code
Community
  • 1
  • 1
iProgram
  • 6,057
  • 9
  • 39
  • 80
  • 3
    Possible duplicate of [Swift do-try-catch syntax](http://stackoverflow.com/questions/30720497/swift-do-try-catch-syntax) – rkyr Nov 23 '15 at 17:36

1 Answers1

2
import Foundation

enum Error:ErrorType {
    case Error1
    case Error2
}

func foo() throws -> Void {
    switch arc4random_uniform(3) {
    case 0: throw Error.Error1
    case 1: throw Error.Error2
    default:
        return
    }
}
for i in 0...6 {
    do {
        try foo()
        print("no error code")
        // you can put here as much
        // code, as you need
        let i = random() % 100
        let j = random() % 100
        let k = i + j
        print("\(i) + \(j) = \(k)")
    } catch Error.Error1 {
        print("error 1 code")
    } catch Error.Error2 {
        print("error 2 code")
    }
}

with result

no error code
83 + 86 = 169
error 1 code
error 2 code
error 1 code
no error code
77 + 15 = 92
error 2 code
no error code
93 + 35 = 128

and be careful, don't mix error and exception. those are totally different concepts

in your pseudo code

Run and Ceck a function that could throw for All errors
If the function does not throw an error
Do this code
...
If error1
Do this code
If error2
Do this code
user3441734
  • 16,722
  • 2
  • 40
  • 59
  • Can you explain what is happening better please? – iProgram Nov 23 '15 at 19:22
  • if the function doesn't throws an error, all subsequent code in do { } block is executed. if the function throws an error, the subsequent code is not executed. all functions which could throws an error must follow the key word try – user3441734 Nov 23 '15 at 19:34