Open judaco opened 7 years ago
Exceptions
//
// main.m
// Lesson04 - ErrorHandling
//
// Created by hackeru on 22/03/2017.
// Copyright © 2017 juda. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MyException : NSException
@property int errorCode;
@end
@implementation MyException
@end
int divide (int x, int y);//the signature of the method, which is outbound of the Main - this is coming from #C lang.
int main(int argc, const char * argv[]) {
@autoreleasepool {
// NSArray *arr = [NSArray array];
// @try {
// @throw [[NSException alloc] initWithName:@"my name" reason:@"my reason" userInfo:nil];//initializer not default, because we have params,
// id x = [arr objectAtIndex: 2];
// NSLog(@"after the error");
// } @catch (NSException *exception) {
// NSLog(@"some error occured %@", exception.reason);//name gives NSRangeException, reson gives NSArray object index exception, index 2 beyond bounds for empty NSArray
// } @finally {
//
// }
@try {
NSLog(@"done %i", divide(8, 0));
} @catch (MyException *exception) {
NSLog(@"some error ocurred - %@ - %@ - %i", exception.name, exception.reason, exception.errorCode);
} @catch (NSException *exception){
NSLog(@"regular exception");
} @finally {
}
NSLog(@"done");
}
return 0;
}
int divide (int x, int y) {
if (y == 0){
MyException * e = [[MyException alloc] initWithName:@"arithmethic exception" reason:@"division by zero" userInfo:nil];
e.errorCode = 404;
//@throw e;
@throw [[NSException alloc] initWithName:@"regular ex" reason:@"no real reason" userInfo:nil];
}
return x/y;
}
//
// main.m
// Lesson04 - Initializers
//
// Created by hackeru on 22/03/2017.
// Copyright © 2017 juda. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Dog : NSObject
-(void) bark;
-(void) goToSleep;
-(void) setName: (NSString *) n;
-(NSString *) getName;
@end
@implementation Dog
{
NSString *name;
int age;
}
//go look at the Dog = (Dog *) - this is an override
-(instancetype)init{
self = [super init];
if (self) {//like boolean, if self is not nil (=0)
name = @"snoopy";
age = 0;
}
return self;
}
-(instancetype)initWithName: (NSString *) n{
self = [super init];
if (self) {//like boolean, if self is not nil (=0)
name = @"snoopy";
age = 0;
}
return self;
}
-(void)bark {
NSLog(@"Waf waf");
}
-(void)goToSleep {
NSLog(@"Zzzzzz");
}
-(void)setName:(NSString *)n {
name = n;
}
-(NSString *)getName {
return name;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dog *d = [Dog alloc];//alloc is static - give us a place in the memory (allocate us a place)
d = [d init];//init is not static, init sets on an object from specific type (here dog)
[d setName: @"peter"];
[d init];
NSLog(@"name: %@", [d getName ]);
}
return 0;
}