Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Creating, throwing, and catching exceptions are virtually identical in Objective-C and Java. Listing 14-1 shows some simple exception handling.
|
Code View:
Scroll
/
Show All 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");
}
}
Code View:
Scroll
/
Show All 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
|