java - 无法向覆盖的方法添加 throws 子句导致我必须返回 null

标签 java android android-asynctask polymorphism

我目前正在使用 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/

相关文章:

java - 使用 JDBC 连接将记录插入到 Apache Ignite Cluster 时出现异常

java - 使用 Java 重命名文件后,在 linux 系统上或通过 Java 无法访问某些文件

java - Android按钮图片抖动动画

android studio 无法解析符号 id

android - 如何在 Kotlin 中将 if 表达式转换为 when

Java - SAXParser 和 XMLReader 获取 null 属性值

java - 使用 Heroku,如何在部署应用程序时自动启动未绑定(bind)到端口的 Java 应用程序?

java - Android AsyncTask异常和onPostExecute

java - 为什么模拟不能与 AsyncTask 一起工作?

java - AsyncTask URLConnection MVP 设计模式