我目前正在使用 AsyncTask 并在 doInBackground
方法中运行一段需要处理特定异常的代码。由于 doInBackground
方法被覆盖,我无法向该方法添加 throws 子句。我插入了一个捕获异常的 try-catch 方法,但由于我的方法返回一个 Summoner 对象,我不得不包含一个 return null;
语句,我发现我的代码仍在执行该语句。
我对 AsyncTask 的经验非常有限,所以如果您需要更多信息或者我在这里忽略了什么,请随时指出。
public class GetSummonerData extends AsyncTask<String, Void, Summoner>
{
@Override
protected void onPreExecute()
{
Button button = (Button) findViewById(R.id.btnSearch);
button.setText("Loading...");
}
@Override
protected Summoner doInBackground(String... asyncParams)
{
try
{
String summonerName = asyncParams[1];
RiotApi api = new RiotApi("api-key");
Map<String, Summoner> summoners = null;
//The following line of code will call the API
summoners = api.getSummonersByName(Region.valueOf(asyncParams[0]), summonerName);
//stage 1
return summoners.get(summonerName);
}
catch (RiotApiException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Summoner result)
{
//stage 2
startNewIntent(result);
}
}
public void startNewIntent(Summoner summoner)
{
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("summoner", summoner);
startActivity(intent);
}
在第 1 阶段,summoners
变量保存 1 个 Summoner 对象。在第 2 阶段,onPostExecute
中的返回结果为 null。为什么try block 中有return语句,却执行了return null?
最佳答案
之所以执行return null
是因为在try-catch
block 中抛出了异常。这会导致 try
block 的所有剩余执行被中止(包括 return 语句)并改为执行 catch
block 。
一旦 catch block 退出 return null
之后就会执行,因为执行会照常进行。
关于java - 无法向覆盖的方法添加 throws 子句导致我必须返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732995/