为什么下面的代码在运行时不会抛出算术错误 -> 1/0;
printf("in start\n");
int i=1/0;
//int o=i;
NSString* myString = [@(i) stringValue];
printf("%s", [myString UTF8String]);
printf("\nafter start\n");
控制台:
in start
-1074745488
after start
最佳答案
它不会抛出错误,因为它是纯 C — 而 C 不知道如何抛出错误。
如果你像这样进入Objective-C的客观世界
NSDecimalNumber *i = [NSDecimalNumber decimalNumberWithDecimal:[@(1) decimalValue]];
NSDecimalNumber *o = [NSDecimalNumber decimalNumberWithDecimal:[@(0) decimalValue]];
NSDecimalNumber *x = [i decimalNumberByDividingBy:o];
你会看到
*** Terminating app due to uncaught exception 'NSDecimalNumberDivideByZeroException', reason: 'NSDecimalNumber divide by zero exception'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff870cf50c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff8abd076e objc_exception_throw + 43
2 CoreFoundation 0x00007fff870cf3bd +[NSException raise:format:] + 205
3 Foundation 0x00007fff8a476ec5 -[NSDecimalNumberHandler exceptionDuringOperation:error:leftOperand:rightOperand:] + 242
4 Foundation 0x00007fff8a475cab _checkErrorAndRound + 57
5 Foundation 0x00007fff8a47606c -[NSDecimalNumber decimalNumberByDividingBy:withBehavior:] + 159
6 devisonByZero 0x0000000100000e54 main + 484
7 libdyld.dylib 0x00007fff8aaa45c9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
但是您实际上可以决定,会发生什么:
NSDecimalNumberHandler *h = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:1
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
NSDecimalNumber *x = [i decimalNumberByDividingBy:o withBehavior:h];
x
现在将是 NaN
。
但 apple 还提供了可识别计算错误的 C 类型:NSDecimal
NSDecimal one = [@1 decimalValue];
NSDecimal zero = [@0 decimalValue];
NSDecimal result;
NSCalculationError error = NSDecimalDivide(&result, &one, &zero, NSRoundPlain);
switch (error) {
case NSCalculationNoError:
NSLog(@"result: %@", [NSDecimalNumber decimalNumberWithDecimal:result]);
break;
case NSCalculationDivideByZero:
NSLog(@"division by 0");
break;
default:
NSLog(@"some calculation error");
break;
}
关于objective-c - 在 Objective-C 中除以零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28514145/