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.
Which is the best exception to use? Or: how to deal with a misconfigured Activity? [closed]
-
02-06-2022 - |
题
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
}
}
解决方案