do - catch

Hi ,


Is there any way to get callback when there is NO error by do-catch in swift ?


Because I think if it is possible, I can use it as callback functon.


Thanks ^^

Accepted Reply

This thread has been deleted

Consider this code:

{
    defer {
        C1()
    }
    do {
        try A()
        C2()
    } catch {
        C3()
        B()
    }
    C4()
}

Here’s how things pan out:

  • C1
    will run no matter what happens with the remaining code
  • C2
    will run if
    A
    does not throw
  • C3
    will run if
    A
    throws
  • C4
    will run if:
    • A
      does not throw
    • A
      throws but
      B
      catches the error

Any questions?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

Do you mean something like a [hypothetical] do-catch-else construct? If so, you can already do that by putting "else" part inside but at the end of the "do" block. For example, instead of something like this:


     do {
          A ()
     }
     catch {
          B ()
     }
     elseifnocatch {
          C ()
     }


you can just do this:


     do {
          A ()
          C ()
     }
     catch {
          B ()
     }


Or have I misunderstood what you meant?

Does that mean you want to get a callback on a non-error?


Callback to do what?


Perhaps if you gave an example of the broader code involved and what it is you're trying to accomplish, etc., thanks.

Hi, QuinceyMorris


Thanks,


and How do I code elseifnocatch part ?


  1. do {
  2. A ()
  3. }
  4. catch {
  5. B ()
  6. }
  7. else {// Consecutive statements on a line must be separated by ';' compile ERROR
  8. C ()
  9. }


this does not work..

vvery interesting answer.


butI do not understand C4 case. If B catches, why is C4 executed and not only the defer ?

Because if an error is caught, execution continues with the statement after the do/catch construct.


IOW, once an error is caught, the sequence of execution returns to normal.


Note, for completeness, there are two cases where this is not true, for obvious reasons:


1. If a "try" statement within the catch block throws.


2. If the catch block executes a "throw" statement.