0

This is a bit of an academic question, but I'm curious to get your input.

I have an Activity which is loosely parameterized by a type string. When creating the Activity, I will always pass in the proper type via Intent's putExtra(). But I only want that string to have a single value, and for various reasons I don't want to hard code it (though I'm weighing the idea).

At any rate, like a good writer of maintainable Java code, I will throw an exception in order to catch the high-level bug of an incorrect type value. I plan to use IllegalArgumentException. Is there a semantically better choice?

Perhaps the better question is: how best to deal with an Android Activity that is just plain configured wrong, after it is launched?

public class MyActivity {

   private String type;

   @Override
   protected void onCreate(Bundle sharedInstanceState) {
      super.onCreate(sharedInstanceState);

      Intent intent = getIntent();
      this.type = intent.getStringExtra("type");

      if (this.type == null || !this.type.equals("the proper type")) {
         // is there something semantically better?
         throw new IllegalArgumentException("You're doing it wrong.");

         // perhaps it's better just to toast.show(), Log.e(), and finish()?
      }

      // ... etc
   }
}
QED
  • 9,803
  • 7
  • 50
  • 87
  • Slightly unrelated, but you might consider using an enum to define what are the valid "parameters" for your Activity. (I believe enums are implicitly Serializable, so you can pack them into Intent extras) – Karakuri Jul 07 '13 at 00:06

1 Answers1

3

I would say, if you are shipping this as a library and want your code to look super-neat, declare your own exception (subclass RuntimeException) and throw it. Definitely no need to bother about toasts, etc when you are handling a programmatic error, not something that a user can fix.

Evgeny Tanhilevich
  • 1,119
  • 1
  • 8
  • 17
  • Accepting before they close my question. I did change from IllegalArgumentException to RuntimeException. – QED Jul 07 '13 at 02:13