【发布时间】:2016-07-14 16:24:46
【问题描述】:
我有这段代码,它没有按预期工作:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_feedback: {
try {
Intent intent_email = new Intent(Intent.ACTION_SEND);
intent_email.putExtra(Intent.EXTRA_EMAIL, new String[]{"feedback@xyz.com"});
intent_email.putExtra(Intent.EXTRA_SUBJECT, "Feedback");
intent_email.setType("message/rfc822");
startActivity(intent_email);
return true;
} catch (Exception e) {
Toast.makeText(getBaseContext(), "No Mail app found", Toast.LENGTH_SHORT).show();
}
}
case R.id.action_rate: {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + getPackageName())));
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "No Market app found", Toast.LENGTH_SHORT).show();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
此代码的问题在于,当 case R.id.action_rate: 中存在异常时,它会显示一个 Toast,为 No Market app found 但是当异常在 case R.id.action_feedback: 中时,它会显示两个 Toast,首先是 未找到邮件应用,然后未找到电子市场应用。意味着它进入两个 catch 块。谁能解释一下它是如何工作的?
但是,我通过将try 块放在switch 语句之前并将catch 块放在switch 语句关闭之后使我的代码正常工作。但是我还是不知道事情的进展如何?
在此先感谢 :)
【问题讨论】:
标签: java android exception-handling switch-statement