Objective c exception handling LEARNOVITA

Exception handling in iPhone: A Definitive Guide with Best Practices [ OverView ]

Last updated on 04th Nov 2022, Artciles, Blog

About author

Yokeshwaran (Sr Software Engineer )

Yokeshwaran is a Sr Software Engineer and his passion lies in writing articles on the most popular IT platforms including prometheus, Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies.

(5.0) | 18957 Ratings 2135
    • In this article you will learn:
    • 1.Introduction.
    • 2.Exception Handling.
    • 3.Generating Exceptions.
    • 4.Error Handling.
    • 5.The NSError Class.
    • 6.Error Domains.
    • 7.Capturing Errors.
    • 8.Conclusion.

Introduction:

The exception handling mechanisms are available to OBJECTIVE-C programs are effective ways of dealing with an exceptional conditions. They decouple detection and handling of these conditions and automate a propagation of the exception from a point of detection to point of handling. As a result, code can be more cleaner, simpler to write correctly, and simpler to maintain.

Exception Handling:

An exception is generated at a runtime and these are runtime, error, objective c language as exception handling syntax similar to the c++, java and here use NS exception, NS error.An exception is the special condition but interrupts the normal flow of an execution objective c has a four exception compiler directives. They are:

  • @try
  • @catch
  • @finally
  • @throws

Try Black:

Try black holds a code that can potentially throw the exception that is enclosed in try block.

Syntax:

  • @try
  • {
  • Int x;
  • Scan f ( “%d”, &x);
  • Int y = 2/x;
  • }

Catch Block:

A catch block contains an exception handling logic for the exception throw in a try block.

Syntax:

  • @ catch (NS argument exception * aex)
  • {
  • }
  • @catch(NS exception * ex)
  • {
  • }

Finally block:

This block is an optional and it contains code for a declaration of resources.

Syntax:

  • @finally
  • {
  • }

NS exception classes are the base class for all exception-related classes.

Exception Handling

Throws:

By using a throws, can rise over a own exception.

Exception Handling and Memory Management:

Using an exception-handling directives of an Objective-C can complicate memory management, but with the little common sense can avoid the pitfalls. To see how, let’s begin with a simple case: a method that, for a sake of efficiency, creates an object, uses it, and then releases it explicitly:

  • – (void)doSomething {
  • NSMutableArray *anArray = [[NSMutableArray alloc] initWithCapacity:0];
  • [self doSomethingElse:anArray];
  • [anArray release];
  • }

The problem here is so obvious: If the doSomethingElse: method throws the exception there is memory leak. But solution is equally obvious: Move a release to a @finally block:This pattern of using @try…@finally to be release objects involved in the exception applies to the other resources as well. If have malloc’d blocks of a memory or open file descriptors, @finally is the good place to free those; it’s also ideal place to unlock any locks have acquired.Another, more a subtle memory-management problem is an over-releasing an exception object when there are an internal autorelease pools. Almost all the NSException objects are created autoreleased, which assigns them to nearest (in scope) autorelease pool. When that pool is released, an exception is be destroyed. A pool can be either released directly or as result of autorelease pool further down the stack being popped .

Generating Exceptions:

Let’s start by taking look at a default exception-handling behavior of the program. The objectAtIndex: method of NSArray is explained to throw an NSRangeException (a subclass of NSException) when try to access an index that doesn’t exist. So, if request the 10th item of an array that has a only three elements.When it encounters the uncaught exception, Xcode halts a program and points to the line that caused a problem.

Error Handling:

Whereas an exceptions are designed to let programmers know when things have gone fatally be wrong, errors are designed to be efficient, straightforward way to check if action succeeded or not. an Unlike exceptions, errors are designed to be used in a everyday control flow statements.

Error Handling

The NSError Class:

The one thing that errors and an exceptions have in common is that they are both implemented as a objects. The NSError class encapsulates all of necessary information for a representing errors:

Code – An NSInteger that represents an error’s unique identifier.

Domain – An instance of NSString defining domain for an error.

UserInfo – An instance of NSDictionary that contains the application-specific information related to error. This is typically used much more than userInfo dictionary of NSException.

In addition to these core attributes, NSError also stores a several values designed to aid in rendering and processing of errors. All of these are actually shortcuts into as userInfo dictionary.

LocalizedDescription – An NSString containing a full description of the error, which typically includes a reason for the failure. This value is typically displayed to user in an alert panel.

LocalizedFailureReason – An NSString containing stand-alone description of reason for the error. This is only used by clients that need to isolate the reason for an error from its full description.

RecoverySuggestion – An NSString instructing user how to recover from error.

LocalizedRecoveryOptions – An NSArray of titles used for a buttons of the error dialog. If this array is empty, single OK button is displayed to dismiss alert.

Error Domains:

An error domain is like the namespace for error codes. Codes should be unique within single domain, but they can overlap with a codes from other domains. In addition to preventing a code collisions, domains also provide an information about where the error is be coming from.The NSCocoaErrorDomain contains error codes for the many of Apple’s standard Objective-C frameworks; however, there are some frameworks that explain their own domains (e.g., NSXMLParserErrorDomain).If need to create a custom error codes for the libraries and applications, should always add them to r own error domain-never extend any of the built-in domains. Creating a own domain is a relatively trivial job. Because of domains are just strings, all have to do is explain a string constant that doesn’t conflict with any of other error domains in the application. Apple suggests that are domains take a form of com.<"company">.<"project">.ErrorDomain.

Capturing Errors:

There are no dedicated language constructs for the handling NSError instances They are designed to be used in a conjunction with specially designed functions that are return an object when they succeed and nil when they are fail. The general procedure for the capturing errors is as follows:

1. Declare an NSError variable. don’t need to allocate or be initialize it.

2. Pass that variable as a double pointer to the function that may result in error. If anything goes wrong, a function will use this reference to record information about an error.

3. Check a return value of that function for the success or failure. If an operation failed, can use NSError to handle error or display it to the user.

Conclusion:

Exceptions are designed to be inform programmers of fatal problems in program, whereas errors represent a failed an user action. Generally, a production-ready application should not throw the exceptions, except in the case of truly exceptional circumstances.

Are you looking training with Right Jobs?

Contact Us

Popular Courses