Tuesday, March 15, 2016

IOS Exceptions - Objective C


Hello everyone,

   As part of the teaching process on IOS-Development, today I am going to show you guys a little bit more about exceptions in Objective-C.

  I would say that in Objective-C you don’t see that much as you can see in Java Exceptions. But I do like and I add in my code as much as needed .Try/catch/finally blocks can be useful to capture errors that may otherwise cause an app to fail. So, yes, please use them.

  In this simple example below I am allocating an array, but I am not adding any elements on it. Inside the try block the attempt to access the first element will cause an exception to be thrown. So, that’s the easiest way to see something happening, right? Let’s go!




The output of the code is shown below:
iPhoneApp[4769:b601] NSException caught
iPhoneApp[4769:b601] Exception Name: NSRangeException
iPhoneApp[4769:b601]  Exception Reason: *** -[NSArray objectAtIndex:]: index 0 beyond bounds for empty array
iPhoneApp[4823:b601] In finally block

The @finally clause as in java is called, it's called anyway. So, this is perfect place to add some methods such as code cleanup, connections released and so on.
Using exceptions can be very helpful when working with files (eg: exampleNSFileHandleOperationException), when working with data from unknown sources it helps a lot.

Catching or Throwing specific exceptions by the usage of method call, check it out:



I hope you liked and talk to you soon!

I hope it helps and happy coding,
Thiago Leoncio

------------------------------------------------------
Other great IOS articles:

IOS - 3 big reasons why start coding in swift instead of Objective-C

IOS - IOS App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure.

IOS - Video using 3D framework

IOS - Video Application with Json and Mysql connection

IOS - How to create Multiple views

No comments:

Post a Comment