Using XCTest, a test does the following:
XCTAssertThrowsSpecificNamed([does something that breaks], NSException, NSInvalidArgumentException);
I don't want the debugger to stop on the NSException that I know will occur but I want it to still stop on other exceptions that might occur.
Basically we don't have a choice. I still consider it an xCode bug because you already told xCode an exception will be thrown, and what exception it will be. Why provide XCTAssertThrows if it's an exception you're not "expecting"?
Obviously it's for exceptions you are expecting, which #nhgrif argues should be an error, not an exception. Might be a good point, but i do want my program to crash if this case ever happens, because I can't handle it.
So the real question is more why not disable the debugger on that exception only? Probably because they haven't gotten around to it. I'd suggest opening a bug/feature request with Apple. I'd love for someone to contradict me on this (please comment!) but until then, I'll live with this issue (disable debugger when running all my tests).
--> https://stackoverflow.com/a/22393643/1701430
"Why does the test stop when the execution is thrown?"
Because you have a breakpoint, which stops execution.
"Why, after removing the breakpoint, does my application crash when the exception is thrown?"
Because you have an unhandled exception. Unhandled exceptions cause your program to crash.
"How can I handle an exception so it won't crash my program?"
The easy answer to this question is to simply NOT throw an exception. In other programming languages, like Java, this is perfectly standard. But in Objective-C, we don't really do exceptions. In Objective-C, exceptions should be saved for TRULY exceptional behavior.
With that said, and a strong suggestion for you to find another way to handle whatever it is you're trying to handle, this is how you handle an exception in Objective-C:
#try {
// code that could throw an exception
}
#catch (NSException *e) {
// handle the exception...
}
#finally {
// post try-catch code, executed every time
}
Related
I notices some code that made me think the Exception function call was optional? E.g., do these two lines perform the same function?
throw Exception('oops!');
throw 'oops!'
No.
The former, throw Exception('oops!');, creates a new Exception object using the Exception constructor, then throws that object.
It can be caught by try { ... } on Exception catch (e) { ... }.
The latter, throw 'oops!'; throws the string object.
It can be caught by try { ... } on String catch (e) { ... }.
Generally, you shouldn't be doing either.
If someone made an error, something that would have been nice to catch at compile-time and reject the program, but which happens to not be that easy to detect, throw an Error (preferably some suitable subclass of Error).
Errors are not intended to be caught, but to make the program fail visibly. Some frameworks do catch errors and log them instead. They're typically able to restart the code which failed and carry on, without needing to understand why.
If your code hit some exceptional situation which the caller should be made aware of (and which prevents just continuing), throw a specific subclass of Exception, one which contains the information the caller needs to programmatically handle that situation. Document that the code throws this particular exception. It's really a different kind of return value more than it's an error report. Exceptions are intended to be caught and handled. Not handling an exception is, itself, an error (which is why it's OK for an uncaught exception to also make the program fail visibly).
If you're debugging, by all means throw "WAT!"; all you want. Just remove it before you release the code.
I'm using the library called CwlPreconditionTesting which is used to test Swift assertions. It uses Mach exceptions handler API to catch exceptions that's available on iOS and OS X.
The library works well in simulators, but devices aren't supported by it. The reason for this is that on devices, the Swift assert functions (e.g. fatalError) crash with EXC_BREAKPOINT exception type, which is also the exception type the debugger uses when someone puts a breakpoint somewhere and the debugger wants to suspend the program. The underlying assembly instruction is brk.
I wanted to add device tests support to the library, but after setting up the exception handler, if the debugger reaches a breakpoint I added manually, the debugger just hangs. To bypass this, I tried to make the exception handler forward the handling of the exception to the debugger.
When I implement an exception handler, if it returns with a failure (i.e. anything other than KERN_SUCCESS), the kernel should forward it to the next exception handler in line, the debugger in my case. I didn't find any official documentation on this, but it says so here and in a piece of code from Mike Ash's blog:
// Handle EXCEPTION_DEFAULT behavior
kern_return_t catch_mach_exception_raise (mach_port_t exception_port,
mach_port_t thread,
mach_port_t task,
exception_type_t exception,
mach_exception_data_t code,
mach_msg_type_number_t codeCnt)
{
// Do smart stuff here.
fprintf(stderr, "My exception handler was called by exception_raise()\n");
// Inform the kernel that we haven't handled the exception, and the
// next handler should be called.
return KERN_FAILURE;
}
Even if I always return KERN_FAILURE, the debugger hangs when I pause at a breakpoint. Here's a screenshot from the Variables View in Xcode, which loads indefinitely:
Is there a way to set up an exception handler and live in peace with LLDB?
When i call this function few times from my button (like mad more then few times), then my app crash instead of just throw exception and ignore.
How do you ignore to crash when exception happened?
where localView is UIView *localView.
- (void)smallLocalView {
#try {
self.localView.backgroundColor = [UIColor blackColor];
[self.localView.layer removeFromSuperlayer];
//self.localView.opaque = NO;
}
#catch(NSException *exp) {
//NSLog(#">>> failed %#" , exp.reason);
NSLog(#"OK - but dont crash!!!");
}
#finally {
NSLog(#"OK - but dont crash!!!");
}
}
EDIT:
tl;dr In general you shouldn't try to catch exceptions, you should try to fix the root cause.
There are two kinds of exception you are interested in. The first kind as shown in your image is a system exception. The processor has encountered a problem, for example trying to access protected memory (usually called by trying to dereference a null pointer). You cannot catch that kind of an exception. The operating system will terminate your program when one is raised.
The problem, by the way, is almost certainly caused by localView having been deallocated prematurely, or maybe you access it not on the main thread (as per Edgar's answer).
The other kind of exception is the Objective-C exception which is always raised programmatically. Although you can catch these with a #try { ... } #catch { ... } block, in general you should not. The reason is that there is no enforcement to make code exception safe, so the exception may unwind stack frames where resources need to be deallocated or stack frames where clean up is needed to keep data structures consistent. Once an exception is thrown and caught, you cannot guarantee the logical consistency of your program's state. Your only real option is to terminate as cleanly as possible.
Make sure you are on the Main thread when changing the background color.
You can add an assert at the beginning, like this, other check the stack trace on the left side when you get the exception in order to check in which thread you're on:
NSAssert([NSThread isMainThread]);
Also, depending on where you are calling smallLocalView from, it might happen that your view is not loaded/ready.
- (void)smallLocalView {
if (!self.isViewLoaded) {
return;
}
...
}
I'm running into a situation in iOS (and OS X) where exceptions from NSKeyedUnarchiver cause binary-only third-party frameworks to crash my app (when deployed in the field) when they try to unarchive a corrupt archive, thus forcing users to delete and reinstall the app. This doesn't happen often, but I'd like that number to be zero.
I can't solve the problem by wrapping the NSKeyedUnarchiver calls, both because I don't have the source code and because those calls are not the direct result of anything that my code does; they run on arbitrary background threads at arbitrary times.
I'm currently swizzling the NSKeyedUnarchiver class so that reading a corrupt archive returns nil (as though the file were not there) rather than throwing an exception, but I can't be certain whether any of those third-party frameworks might do things correctly (with an #try/#catch block) and might break in interesting ways if I do so.
It would be helpful if I could somehow examine the Objective-C exception handling tree (or equivalent) to determine whether an exception handler would catch an exception if thrown, and if so, which handler. That way, my patched method could return nil if the exception would make it all the way up to Crashlytics (which would rethrow it, causing a crash), but could rethrow the exception if some other handler would catch it.
Is such a thing possible, and if so, how?
Why not wrap your exception-throwing callsite in a try/catch/finally?
#try {
//call to your third party unarchiver
}
#catch {
//remove your corrupted archive
}
#finally {
//party
}
Rolling your own global exception handler may also be of use here, ala: How do you implement global iPhone Exception Handling?
If you're not sure that wrapping third-party library code with #try/#catch is good enough you can hook NSKeyedUnarchiver methods to replace them with exact same wrapper thus making sure that exception is never gets thrown outside. Here is pseudo-code:
#try {
//call original NSKeyedUnarchiver implementation
}
#catch {
return nil;
}
Objc runtime has public APIs that can do such a thing
I'm writing Cocoa unit tests using XCTest and recently used XCTAssertThrows for the first time. That's pretty cool, but I want to make it even better with XCTAssertThrowsSpecific and requiring a certain exception.
Here is an example test:
-(void)testShortPassword {
XCTAssertThrows([user storePassword:#"abc"],#"Expect exception for short pw");
}
And on my user class I have the following code:
-(void)storePassword:(NSString*)password {
NSCAssert(password.length > 6, #"Password must be longer than 6 characters");
// go on to store the password on the keychain
}
Keeping in mind that Cocoa in general shies away from using exceptions (so it might be better to return an error, and show UI in the preceding example, etc.) How do I throw an exception in a manner that can be caught by XCTAssertThrowsSpecific? How do I specify that in XCTAssertThrowsSpecific(expression, specificException, format...)?
You should only use exceptions for exceptional cases, not for error handling and flow control
Having said that, here's how you use XCTAssertThrowsSpecific:
XCTAssertThrowsSpecific expects the specific class of the exception as the second parameter. NSCAssert throws an NSException. To test for that, use
XCTAssertThrowsSpecific([object methodThatShouldThrow], NSException, #"should throw an exception");
Now, that won't help much, because it's likely that every exception is an NSException or a subclass thereof.
NSExceptions have a name property that determines the type of the exception. In case of NSCAssert this is NSInternalInconsistencyException. To test for that, use XCTAssertThrowsSpecificNamed
XCTAssertThrowsSpecificNamed(
[object methodThatShouldThrow],
NSException,
NSInternalInconsistencyException,
#"should throw NSInternalInconsistencyException"
);