I am developing an Android application that uses multiple UI elements (e.g., Button, TextView, etc.), and I want to perform error handling for these elements. (Note: These elements aren’t created using XML files; everything is done programmatically.)
For example, while setting the Font Variation Settings for any TextView here, they have clearly mentioned that if it fails to set it will raise the Exception.
Similarly when I am trying to create the UI elements which when created programmatically something as shown below:
public fun CreateObject (pContext : Context) : Unit
{
val button_elem : Button
// If this call fails how should this be taken care of?
button_elem = Button (pContext) // Please consider the context as not null
}
It’s a constructor it will not return any value, but it might throw some exception in some rare scenario (for example Out of memory) but nothing such is mentioned in the document here.
Or does Android guarantee that these APIs will never fail? Require some detailed answers to these questions?
Or does Android guarantee that these APIs will never fail?
No. Almost every line of your code could fail, such as with the OutOfMemoryError
that you cite.
// If this call fails how should this be taken care of?
Let the app crash. If you get an OutOfMemoryError
when trying to instantiate a Button
, your process’ heap is beyond repair, and anything else that you try to do will also trigger OutOfMemoryErrors
.
Every constructor may fail. For example, if the pContext
is null, but the constructor used it directly inside, then it will throw an NPE exception.
But for most cases, we don’t need to care about theses. Since exceptions such as OutOfMemoryErrors
is rare and offical APIs can gurantee it won’t throw such exceptions. If it happened, we could just let the App crash.
What we need to do is to watch these exceptions, and solve it if necessary. For example, if OutOfMemoryErrors
happened, it usually some other places in our project caused this error. So, we need solve that issue in our project.
You can use Firebase Crashlytics
to watch these errors: https://firebase.google.com/docs/crashlytics
You can also use Thread#setDefaultUncaughtExceptionHandler
method to watch exceptions in Java layer.