Exception Handling

Sorry, I'm a newbie, so the questions may seem silly:
How do I know if a function can return an exception?
(I couldn't find anything about it in the documentation)
If there can be no exceptions, then what happens if I pass invalid data to a function or if the operating system does not have enough resources to allocate memory for a new object?
For example, here is a part of the code:
Code Block C++
runLoopMachPort = CFMachPortCreateRunLoopSource(
kCFAllocatorDefault,
eventTab,
0);
CFRunLoopAddSource(
CFRunLoopGetCurrent(),
runLoopMachPort,
kCFRunLoopCommonModes);

1) Can the CFRunLoopAddSource function return an exception?
2) How do I understand that the CFRunLoopAddSource function did not have enough memory to add new data? (and in general, how to find out about any other problems)

I'm a newbie, so the questions may seem silly

These are so not silly questions: The concept of exceptions is fundamentally complex. I’ve been meaning to write this up for a while, so I used your question as an excuse to do that. Read What is an exception? before continuing.



With regards your specific questions:

If there can be no exceptions, then what happens if I pass invalid
data to a function … ?

That depends. Cocoa’s general philosophy is that the invalid data represents a programming error then the routine will trap, either directly or by throwing a language exception that you shouldn’t try to catch. If, on the other hand, this is not an error that you can reasonably anticipate, the routine will return some sort of error status.

For example, the API contract for NSMutableDictionary says that you mustn’t call setObject:forKey: with a nil key. If you do, the method will trap. OTOH, if you call -objectForKey: with a key that’s not in the dictionary you’ll get back an error status (in this case nil). In some cases that error status is very clear — there’s only one way that -objectForKey: can fail — but in other cases there could be a wide variety of potential errors and thus the method has an NSError ‘out’ parameter.

if the operating system does not have enough resources to allocate
memory for a new object

That depends on the type of the resource. For memory (well, address space) there’s two ways to slice this:
  • If the allocation is large, the routine returns an error status.

  • Otherwise the routine will trap.

The second point may come as a surprise but it makes sense. If your process is so short on address space that you can’t allocate a small item, like an object, it’s not going to run for long anyway.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Exception Handling
 
 
Q