3

Suppose the following situation in Objective-C: an array of blocks.

So I want to run a block, I do:

myBlock block = blocks[0](); 

Now imagine that this line runs inside a try:

myBlock block = blocks[0];
@try {
  block();
} @catch {
  // catch an error
}

Now imagine that I want add a line inside a block to force the catch.

What I did in objective-C was to add this line inside a block

[NSException raise:@"Failed" format:@"Failed", nil];

Now I want to do that in Swift

let myClousure = closures[0]

do {
   myClosure!()
} catch {
}

The question is: what line should I add to a closure to force the same behavior, or in other words, to make the closure fail and the catch to be triggered?

Sorry if the question is stupid but I am new to Swift.

Duck
  • 34,902
  • 47
  • 248
  • 470
  • Have a look at https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html . – Martin R Aug 26 '19 at 18:02
  • Possible duplicate of [Error-Handling in Swift-Language](https://stackoverflow.com/questions/24010569/error-handling-in-swift-language) – Martin R Aug 26 '19 at 18:06
  • @MartinR - I started testing swift years ago. Then stopped using it because professionally no one cared about swift back then. A few weeks ago I started using swift professionally. So, yes, I am new to swift. – Duck Aug 26 '19 at 18:12

1 Answers1

3

In Objective-C, you use @try/@catch blocks to handle ObjC exceptions such as the one you are raising. In Swift, you use do/catch blocks to catch Swift errors that are explicitly thrown from a "throwing" function. Only functions (and closures) marked with the "throws" keyword are allowed to throw an error, and if you call a function that can throw, you must handle the error.

If you have an array of closures, the type signature of the closure must specify that it can throw, e.g.

let blocks: [() throws -> Void] = // get some blocks

At this point, you can (and indeed must) handle any errors thrown by calling these blocks:

let block = blocks[0]
do {
    try block()
} catch let error {
    print(error)
}
dalton_c
  • 6,876
  • 1
  • 33
  • 42