iPhone development: How to Catch Exception/NSError in Objective-C?
exception, iphone, memory-management, objective-c
Solution
Objective-C is an unmanaged runtime; the code that you compile runs directly on the CPU rather than in a virtual machine. That means you don't have the supervisory layer that can trap every possible failure mode the way you do when running in the .NET VM or the JVM. The long and short of it is that the only way you're going to be completely sure a program can't crash is to code very carefully and test very thoroughly. And even then, you're not sure, you just think you are.
The latest version of Xcode integrates the Clang static analyzer ('Build and Analyze' in the Build menu) that can identity some classes of potential bugs -- I'm fairly sure it would flag your example above, for instance). But there is no magic bullet here; the only solution is hard work.
Problem
I want my application to never just crash stupidly. I know that code quality is the root solution for this. But I still need an application to never crash when some unexpected bug happens. Here is code I want to try. ``` -(void)testException { @try { NSString* str; [str release]; } @catch(NSException* ex) { NSLog(@"Bug captured"); } } ``` I know this one does not work. Because `release` never raise an exception. Here are my questions: - How to reach this kind of objective, bug will be captured, no crash? - How do I know which system library will raise exception and so I can write some code and know it works? Here's what I have read - a. Exception Programming Topics for Cocoa - b. Error Handling Programming Guide For Cocoa I come from an experienced Microsoft programmer background in which catch exception or unexpected exception always prevent my program from crashing in a very bad environment. How did you guys/gals (Mac genius programmers) make crash free programs happened? Share your experience.