Java:在结束之前尝试阻止,没有任何异常

时间:2013-11-06 16:42:04

标签: java android android-asynctask try-catch

让我疯狂的是我的程序在try块中间停止并且在所有catch块之后连续!这是细节。我得到了AsyncTask

public class BigBitmapLoader extends AsyncTask<Uri, Void, Bitmap>
{

    public BigBitmapLoader(ScribblesView scribbles)
    {
        scribblesRef = new WeakReference<ScribblesView>(scribbles);
    }

    @Override
    protected Bitmap doInBackground(Uri... params)
    {
        InputStream is;
        try
        {
            ScribblesView scribs = scribblesRef.get();
            if (scribs != null)
            {
                is = scribs.getContext().getContentResolver().openInputStream(params[0]);
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                is.close();
                return bitmap;
            }
        }
        catch(FileNotFoundException e)
        {
            Log.e(ERROR_TAG, e.toString());
        }
        catch(IOException e)
        {
            Log.e(ERROR_TAG, e.toString());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap)
    {
        ScribblesView scribs = scribblesRef.get();
        if (scribs != null) scribs.setBigBitmap(bitmap);
    }

    private WeakReference<ScribblesView> scribblesRef;

    private static final String ERROR_TAG = "BigBitmapLoader";

}

在doInBackground()中,它来到is.close(),然后在所有catch块之后立即跳转到return null。因此它会跳过return bitmap。在这一点上,我没有例外。只有在使用返回的位图后才能获得NPE。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

嗯,调试器的行号有时会关闭,所以也许这就是问题所在。做一个干净的构建。 另外,我会将is.close()移动到最后阻止。一般来说,这是一个好主意,以确保您正确处理资源。所以它会是这样的:

InputStream is = null;
try
    {
     // do stuff
} catch(FileNotFoundException e)
{
    Log.e(ERROR_TAG, e.toString());
} catch(IOException e) {
    Log.e(ERROR_TAG, e.toString());
} finally {
  if (is != null) {
     is.close();
  }
}

答案 1 :(得分:2)

由于来自NullPointerException的{​​{1}}你只是看不到它而失败了。当来自isExecutorService的{​​{1}}中发生异常时,吞下异常(除非设置了UncaughtExceptionHandler)。 注意 AsyncTask使用(或至少我检查过的)ExecutorService进行异步执行。

Callable将在另一个线程上运行,如果发生RuntimeException,它将不会打印未指定的任何地方(即吞下异常)。

我建议你添加第三个catch块

Runnable

简而言之,InputStream可能为null。

答案 2 :(得分:1)

您没有看到例外,因为没有例外

        ScribblesView scribs = scribblesRef.get();
        if (scribs != null)
        {
            is = scribs.getContext().getContentResolver().openInputStream(params[0]);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return bitmap;  // return statement
        }

return语句可能返回null。尝试调试方法“decodeStream”

答案 3 :(得分:0)

原因是我在主线程上有异常。但是在日志中没有链接。这里if (scribs != null) scribs.setBigBitmap(bitmap); setBigBitmap()我使用了未初始化的变量。修正了它并且一切正常。但是debuger仍然“跳跃”。也许在eclipse的debuger中有一些错误,因为现在它返回一个正确值的返回值。并且之前做过。它只是未初始化的变量。 谢谢大家的答案)