Identifying UIKit Api's failure

I have a UIKit application and it contains multiple UI components like UIWindow, UIView, UIButton, etc. I wanted to perform error handling for different OS calls in my application.

For example, when creating a UIImage using init(named:) initialiser, the documentation clearly states that if the UIImage object cannot be created then the initialiser returns nil value.

However, there are other UI components like UIButton (or like UIView), which when created using init(frame:) initialiser, the documentation does not mention for any return value. I wanted to know how to identify If the UIButton initialisation has failed?

How is it that apple recommends should we handle these api's, If they fail to create a button. suppose If there is a case where it fails due to insufficient memory.

Or is it that apple guarantees the Api's never fail?Is there some exception that is throw? I wanted somewhat detailed answer to these questions.

suppose If there is a case where it fails due to insufficient memory.

To address that point specifically:

(On iOS), When memory is low, apps get memory warnings and should free resources. If that’s not enough, suspended apps will be terminated.

The only situation where you will really run out of memory is if you ask for a ridiculously large allocation, and that indicates a bug in your program.

(The same is also true on other platforms, except embedded systems without virtual memory. Unless you run out of virtual address space, memory allocations will always succeed even when physical RAM is exhausted; the problem is dealt with by other mechanisms, such as Linux’s “OOM Killer”. Personally, in my C++ code I assume that memory allocation cannot fail.)

More generally: if the API has some way of reporting an error, try to handle it; if it doesn’t, assume that it cannot fail for valid parameters.

That is not the correct constructor for UIImage. It is actually "init?(named name: String)". That "?" means the method returns an optional. You app is expected to gracefully handle a nil result in this case. It could fail for many different reasons.

But the UIButton constructor does not return an optional. You can assume that it doesn't fail. There is no guarantee, of course. But if the system can't create a UIButton for whatever reason, chances are that the device and app will have long since died for some other reason.

Some APIs will throw an exception instead of returning a nil. The documentation and compiler will clearly identify those cases and you'll be expected to handle them.

Identifying UIKit Api's failure
 
 
Q