I have been trying to make a method where the user can input a value between x and y. A while-loop ensures that the input value stays between x and y, and my try-catch is supposed to throw an exception if the user enters an invalid variable (i.e. user enters “e” when the program expects an integer). The do-while loop serves to loop the method as long as a valid variable has not been entered.
here is my code, when i run it everything runs fine except for when i try to enter an invalid variable (for example if i enter ‘e’ or ‘$’), then my program just loops the code “NSLog(@”Enter a number between %i and %i”, min, max)” infinitely.
#import <Foundation/Foundation.h>
@interface UI : NSObject
{
int a;
int ok;
}
-(int)getInt:(int)min:(int)max;
@end
@implementation UI
-(int) getInt: (int) min: (int) max{
ok = 0;
do {
@try {
NSLog(@"Enter a number between %i and %i: ", min, max);
scanf("%i", &a);
while(a<min || a>max){
NSLog(@"Make sure your number is between %i and %i: ", min, max);
scanf("%i", &a);
}
ok=1;
}
@catch (NSException * e) {
NSLog(@"Error. Re-enter your number");
}
} while (ok=0);
return a;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
UI *ui = [[UI alloc] init];
NSLog(@"The number you entered is %i", [ui getInt:1 :10]);
[ui release];
[pool drain];
return 0;
}
You don’t actually have any code there that throws an exception, so it’s not surprising that no exception is being thrown. To throw an exception you would use @throw.
However, this isn’t how you should do this anyway. Exceptions in Objective-C are nearly always reserved for non-recoverable programming errors, not incorrect user input. You should not use exceptions for normal control flow.