title: Try-Catch to handle Apple exception when scaling UIImage
body: <p>I have a problem with some image-scaling code that throws an exception in iOS5 but works in 6 and 7.</p>
  
  <p>I need to support users running 5 so I am trying to code a try-catch which will call some special iOS5 code when the exception occurs.</p>
  
  <p>The exception (EXC_BAD_ACCESS) seems to happen in Apple code, and the exception handler in my code does not handle the error but the app just immediately crashes.</p>
  
  <p>So, can anyone suggest a more robust way to trying to catch the exception, or can anyone shed any light on a better way of scaling images? (remembering that this is for iOS5)</p>
  
  <p>My main image-scaling function (containing the exception catcher that does not work):</p>
  
  <pre><code>+ (UIImage *)imageWithImage:(UIImage *)image scaledToMax:(int)maxDimension {
  
      // Get a copy of the image where the new image has a maximum height or width as specified by maxDimension
  
      float scaleFactor;
  
      if (image.size.width&lt;=maxDimension &amp;&amp; image.size.height&lt;=maxDimension)
      {
          return image;
      }
  
      if (image.size.width&gt;image.size.height)
      {
          scaleFactor = maxDimension / image.size.width;
  
      } else {
  
          scaleFactor = maxDimension / image.size.height;
  
      }
  
      float newWidth = roundf(image.size.width * scaleFactor);
      float newHeight = roundf(image.size.height * scaleFactor);
  
      CGSize newSize = CGSizeMake(newWidth, newHeight);
  
      UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
  
      NSLog(@"HPSImageHelper imageWithImage point a %f %f", newSize.width, newSize.height);
  
      UIImage *newImage;
  
      @try {
  
          [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
  
          NSLog(@"HPSImageHelper imageWithImage point b");
          newImage = UIGraphicsGetImageFromCurrentImageContext();
          NSLog(@"HPSImageHelper imageWithImage point c");
          UIGraphicsEndImageContext();
  
      }
      @catch (NSException * e) {
  
          NSLog(@"HPSImageHelper imageWithImage point d");
  
          newImage = [image scaleToSize:newSize];
  
          NSLog(@"HPSImageHelper imageWithImage point e");
      }
  
      NSLog(@"HPSImageHelper imageWithImage point f");
  
      return newImage;
  
  
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/udyMT.png" alt="enter image description here"></p>