title: In Objective C/Swift what do return within a method when an error is thrown?
body: <p>Note: I say Objective C/Swift in the title of this post because I believe the answer to this question will apply to both languages, but the code I include in this post is Swift.</p>
  
  <p>Java has a nice mechanism for Exception handling, but in Objective C we're either getting an error back from a delegate method or passing an error into a function by reference and then checking it afterwards. I'm wondering, what is the cleanest way to return from a method which expects a return value (such as an NSString, UIImage, or some other complex object) when an error is thrown? I don't know if "thrown" is the correct word to use in Objective C, but I really just mean when you make a call that returns a non-nil NSError. </p>
  
  <p>For example, say I have this code which is trying to create a UIImage of a QR code:</p>
  
  <pre><code>func createQRImageWithString(string: String, andWidth width: Int32, andHeight height: Int32) -&gt; UIImage {
      var error : NSError?
      let writer : ZXMultiFormatWriter = ZXMultiFormatWriter()
      let result = writer.encode(string, format: kBarcodeFormatQRCode, width: width, height: height, error: &amp;error)
      if (error) {
          println(error!.localizedDescription)
  
      } else {
          let image :CGImageRef = ZXImage(matrix: result).cgimage
          return UIImage(CGImage: image)
      }
  }
  </code></pre>
  
  <p>This func does not compile because in the if statement no UIImage object is returned. The func creates a contract between the func and anyone who uses it, promising that a UIImage will be returned. In the event of an error, I have no UIImage to return. I guess I could make a dummy empty UIImage and return it, but that's certainly not what is expected. So what is the best way to handle this?</p>
  
  <p>I gave an example using UIImage, but I'd like the answer to be generalizable to any situation where a method promises to return an object, but due to an unforeseen error returning that object is not going to go as planned.</p>