views:

32

answers:

1

My custom ViewGroup expects a certain number of strings for an array specified in arrays.xml. I want the app to stop if that condition is not met. What is the best practice for this? Should I just throw an IllegalStateException from the ViewGroup constructor ?

public MyViewGroup( Context context, AttributeSet attrs )
{
    super( context, attrs );
    if( getResources().getStringArray( R.array.carousellabels ).length != 7 )
        throw new IllegalStateException( "There must exactly 7 items for 
             array resource R.array.carousellabels" );
}
A: 

Throwing and handling exception is expensive operation. You can create a factory method that ether returns valid instance (if you get right number of entries) or null. Then you simply check for null and do whatever you need to handle the condition (pop Toast?)

DroidIn.net