Asynctask Error Handling

I am using AsyncTask to perform some background calculations but I am unable to find a correct way to handle exceptions. Currently I am using the following code:

private class MyTask extends AsyncTask<String, Void, String>
{
    private int e = 0;

    @Override
    protected String doInBackground(String... params)
    {
        try
        {
            URL url = new URL("http://www.example.com/");
        }
        catch (MalformedURLException e)
        {
            e = 1;
        }

        // Other code here...

        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (e == 1)
            Log.i("Some Tag", "An error occurred.");

        // Perform post processing here...
    }
}

I believe that the variable e maye be written/accessed by both the main and worker thread. As I know that onPostExecute() will only be run after doInBackround() has finished, can I omit any synchronization?

Is this bad code? Is there an agreed or correct way to handle exceptions in an AsyncTask?

16
задан Leo 12 September 2010 в 18:57
поделиться