Error handling in non-throwing function in Swift

I am having problems with handling errors in non-throwing functions like overridden methods, delegate methods or dataSource methods. I only came up with logging the error and as you know this is not a good error-handling strategy. Is there any other way, approach etc.? Thank you.

EDIT:

enum SomethingError : Error{
    case somethingFailed
}

var anObject : AnObject?

........
........


public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      guard let anObject = anObject else{
            throw SomethingError.somethingFailed
            //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
        }

      .....
      .....

      return cell
}

You cannot do something like this, since :collectionView:cellForItemAt:indexPath is not a throwing function and it must return a cell. How can I catch an error here? This is the question. Only via logging?

EDIT: I know that I can use if let but I want to catch/throw; HANDLE an error here.

Upvotes: 0

Views: 1280

Answers (1)

barbarity
barbarity

Reputation: 2488

You can't propagate errors in implementations of protocols that don't explicitly require them.

You can throw/catch them in the same implementation or simply call a method to handle the error. In your example you can use throw/catch like this:

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      do {

          guard let anObject = anObject else {
              throw SomethingError.somethingFailed
              //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
      } catch SomethingError.somethingFailed {
          // handle the error here
      }

      .....
      .....

      return cell
}

And with just a function it will be something like this:

func handleError() {
    // handle error
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      guard let anObject = anObject else{
            handleError()
            return
        }

      .....
      .....

      return cell
}

For more information about error-handling in swift you can read: The Swift Programming Language: Error Handling

Upvotes: 3

Related Questions