1

I wanna check the UITextField is String or number by using try catch. But it seems doesn't work. Here is my code:

- (IBAction)add {

    @try {
        double firstNumber = self.firstNumber.text.doubleValue;
        double secondNumber = self.secondNumber.text.doubleValue;

        Calculator *calcu = [[Calculator alloc] initWithFirstNumber:firstNumber andSecondNumber:secondNumber andOperation:@"+"];

        self.result.text = calcu.calculateTwoNumber;
    }
    @catch (NSException *exception) {
        self.result.text = @"Please enter right number!";
    }
    @finally {

    }
}
nempoBu4
  • 6,521
  • 8
  • 35
  • 40
user2228647
  • 69
  • 2
  • 8
  • 1
    Well I think the problem is that there's nothing in your `@try` that's throwing an exception... – rebello95 Mar 10 '15 at 04:05
  • 2
    Do not use `try/catch` for such a task. It's not the right tool for the job. – rmaddy Mar 10 '15 at 04:05
  • 2
    What do you think will throw an exception? Calling `doubleValue` on a string that doesn't actually have a number simply returns 0 as stated in the docs. – rmaddy Mar 10 '15 at 04:06
  • I have indented your code so that it renders properly. – nempoBu4 Mar 10 '15 at 04:35
  • Or sending a message to a `nil` value doesn't cause a crash. If `self.result` is nil, nothing happens. – Ozgur Vatansever Mar 10 '15 at 04:37
  • 1
    try-catch should only be used for checking exception. If you want to validate the field, implement your own method to check if the text satisfies your requirements. – huong Mar 10 '15 at 05:01
  • 5
    iOS is not Java. Exception are what they are named "Exceptions" and not error handlers – Thallius Mar 10 '15 at 07:26
  • possible duplicate of [Objective-C Exceptions](http://stackoverflow.com/questions/4648952/objective-c-exceptions) – dandan78 Mar 10 '15 at 07:44

2 Answers2

5

Follow code:

    @try {
       self.labelName.text=[arrName ObjectAtIndex:indexPath.row];
    }
    @catch (NSException *exception) {
        NSLog(@"Something missing...");
    }
    @finally {

    }
siburb
  • 4,880
  • 1
  • 25
  • 34
Mr.Javed Multani
  • 12,549
  • 4
  • 53
  • 52
4

What Claus Bönnhoff wrote in the comments cannot be overemphasized: Objective-C is not Java or C#.

The accepted way to use exceptions in Obj-C is for unrecoverable errors, not simple flow control.

The answer to your question, then, is that exceptions should be used very rarely. In several years of iOS development, I haven't used them a single time. I also have not come accross them in anyone else's code.

I have, however, encountered exceptions thrown by the Obj-C runtime, which I suppose gives some indication of what their role might be.

dandan78
  • 13,328
  • 13
  • 64
  • 78