Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 14. Exception Handling > Using Exceptions

14.1. Using Exceptions

Creating, throwing, and catching exceptions are virtually identical in Objective-C and Java. Listing 14-1 shows some simple exception handling.

Example 14.1. Exception Handling

Java
public class Tosser
{
    public void catcher( ) throws Exception
    {
        try {
            System.out.println("Tosser.catcher(): trying");
            thrower();
        } catch ( SpecificException se ) {
            System.out.println("caught SpecificException: "+se);
        } catch ( Exception e ) {
            System.out.println("caught Exception: "+e);
            throw e;
        } finally {
            System.out.println("Tosser.catcher(): finished");
        }
    }

    public void thrower( ) throws Exception
    {
        throw new Exception("thrower() does not work");
    }

}

					  

Objective-C
@interface Tosser : NSObject

- (void)catcher;
- (void)thrower;

@end

@implementation Tosser

- (void)catcher
{
    @try {
        NSLog(@"%s trying",__func__);
        [self thrower];
    } @catch ( SpecificException *se ) {
        NSLog(@"caught SpecificException: %@",se);
    } @catch ( NSException *e ) {
        NSLog(@"caught NSException: %@",e);
        @throw e;
    } @finally {
        NSLog(@"%s finished",__func__);
    }
}

- (void)thrower
{
    @throw [NSException exceptionWithName:@"MyException"
                                   reason:@"-thrower does not work"
                                 userInfo:nil];
}

@end

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint