Duck
Duck

Reputation: 36013

How to force a catch from a closure?

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.

Upvotes: 3

Views: 80

Answers (1)

dalton_c
dalton_c

Reputation: 7170

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)
}

Upvotes: 3

Related Questions