Java 试一试{ 结果res=点任务(参数); 返回新结果异常(res); }捕获(例外e){ 背景例外(e); 返回新的结果异常(e); } } /** *重写此方法以在后台线程上执行计算。这个 *指定的参数是传递给的参数 *{@link#doTask(Obje

Java 试一试{ 结果res=点任务(参数); 返回新结果异常(res); }捕获(例外e){ 背景例外(e); 返回新的结果异常(e); } } /** *重写此方法以在后台线程上执行计算。这个 *指定的参数是传递给的参数 *{@link#doTask(Obje,java,android,Java,Android,试一试{ 结果res=点任务(参数); 返回新结果异常(res); }捕获(例外e){ 背景例外(e); 返回新的结果异常(e); } } /** *重写此方法以在后台线程上执行计算。这个 *指定的参数是传递给的参数 *{@link#doTask(Object[])}由此任务的调用方执行。这种方法可以 *调用{@link#publishProgress(Object…}在UI上发布更新 *线。 * *@param params *任务的参数。 *@返回此任务的子类定义的结果。 */ 受保护的抽

试一试{ 结果res=点任务(参数); 返回新结果异常(res); }捕获(例外e){ 背景例外(e); 返回新的结果异常(e); } } /** *重写此方法以在后台线程上执行计算。这个 *指定的参数是传递给的参数 *{@link#doTask(Object[])}由此任务的调用方执行。这种方法可以 *调用{@link#publishProgress(Object…}在UI上发布更新 *线。 * *@param params *任务的参数。 *@返回此任务的子类定义的结果。 */ 受保护的抽象结果点任务(Params[]Params); /** *处理调用{@link#onSuccess(Object)}和 *{@link#onFailure(Exception)}方法。 */ @凌驾 PostExecute上受保护的最终无效(结果异常结果){ if(result.getException()!=null){ onFailure(result.getException()); }否则{ onSuccess(result.getResult()); } } /** *在{@link#doTask(Object[])中引发异常时调用。处理 *在后台线程中。 * *@param异常 *抛出的异常 */ 受保护的void onBackgroundException(异常){ } /** *在{@link#doTask(Object[])}方法完成执行时调用 *没有抛出异常。 * *@param结果 *从{@link#doTask(Object[])返回的结果 */ 成功时受保护的无效(结果){ } /** *在{@link#doTask(Object[])中引发异常时调用。处理 *在前景线程中。 * *@param异常 *抛出的异常 */ 失效时受保护的无效(异常){ } } 类ResultException{ /** *可能引发的异常 */ 例外情况; /** *如果没有引发异常,则返回结果 */ TResult-mResult; /** *@param异常 *抛出的异常 */ 公共结果异常(异常){ mException=异常; } /** *@param结果 *从方法返回的结果 */ 公共结果异常(TResult result){ mResult=结果; } /** *@返回异常 */ 公共异常getException(){ 返回异常; } /** *@param异常 *要设置的异常 */ 公共无效集合异常(异常){ mException=异常; } /** *@返回结果 */ 公共TResult getResult(){ 返回mResult; } /** *@param结果 *结果如何 */ 公共void setResult(TResult result){ mResult=结果; } }
如果要在UI线程中执行某些操作(如果引发异常),请不要认为这会起作用。正确,这将在后台运行。我喜欢这个答案,它非常简单。为什么要检查空结果?这是不可能发生的。对,但该代码经过改编,原始代码有时会返回null。您应该检查
异常
是否为null,而不是
结果
。因为如果
realDoInBackground
返回null,那么
onException
将被调用并传递
null
class DownloadAsyncTask extends AsyncTask<String, Void, String> {

    /** this would be cool if it existed */
    @Override
    protected void onError(Exception ex) {
        ...
    }

    @Override
    protected String doInBackground(String... params) {
    try {
            ... download ...
        } catch (IOException e) {
            setError(e); // maybe like this?
        }
    }       
}



     public class AsyncTaskResult<T extends Object> {
            Exception exception;
            T asyncTaskResult;

            public void setResult(T asyncTaskResult) {
                this.asyncTaskResult = asyncTaskResult;
            }

            public T getResult() {
                return asyncTaskResult;
            }

            public void setException(Exception exception) {
                this.exception = exception;
            }

            public boolean hasException() {
                return exception != null;
            }

            public Exception getException() {
                return exception;
            }
        }



    /** this would be cool if it existed */
    protected void onError(Exception ex) {
        // handle error...
    }

    @Override
    protected AsyncTaskResult<String> doInBackground(String... params) {
        AsyncTaskResult<String> result = new AsyncTaskResult<String>();
        try {
            // ... download ...
        } catch (IOException e) {
            result.setException(e);
        }

        return result;
    }       

    @Override
    protected void onPostExecute(AsyncTaskResult<String> result) {
        if(result.hasException()) {
            // handle error here...
            onError(result.getException());
        } else {
            // deal with the result
        }
    }

class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {
    protected abstract void onException(Exception e);

    protected abstract ... realDoInBackground(...);

    protected ... doInBackground(...) {
        try {
            return realDoInBackground(...);
        } catch(Exception e) {
            onException(e);
        }
    }
}
new AsyncTask<Void, Void, Boolean>() {
    Exception error;

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
             // do work
             return true;
        } catch (Exception e) {
            error = e;

            return false;
        } 
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            Toast.makeText(ctx, "Success!",
                Toast.LENGTH_SHORT).show();
         } else {
            if (error != null) {
                Toast.makeText(ctx, error.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {

    private Exception exception = null;

    protected abstract void onResult(Result result);

    protected abstract void onException(Exception e);

    protected abstract ... realDoInBackground(...);

    @Override
    final protected void onPostExecute(Result result) {
        if(result != null) {
            onResult(result);
        } else {
            onException(exception);
        }
    }

    @Override
    protected ... doInBackground(...) {
        try {
            return realDoInBackground(...);
        } catch(Exception e) {
            exception = e;
        }
        return null;
    }
}
public abstract class HandledAsyncTask<Params, Progress, Result> extends
        AsyncTask<Params, Progress, ResultOrException<Result>> {

    /**
     * Wraps the calling of the {@link #doTask(Object[])} method, also handling
     * the exceptions possibly thrown.
     */
    protected final ResultOrException<Result> doInBackground(Params... params) {
        try {
            Result res = doTask(params);
            return new ResultOrException<Result>(res);
        } catch (Exception e) {
            onBackgroundException(e);
            return new ResultOrException<Result>(e);
        }
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to
     * {@link #doTask(Object[])} by the caller of this task. This method can
     * call {@link #publishProgress(Object...)} to publish updates on the UI
     * thread.
     * 
     * @param params
     *            The parameters of the task.
     * @return A result, defined by the subclass of this task.
     */
    protected abstract Result doTask(Params[] params);

    /**
     * Handles calling the {@link #onSuccess(Object)} and
     * {@link #onFailure(Exception)} methods.
     */
    @Override
    protected final void onPostExecute(ResultOrException<Result> result) {
        if (result.getException() != null) {
            onFailure(result.getException());
        } else {
            onSuccess(result.getResult());
        }
    }

    /**
     * Called when an exception was thrown in {@link #doTask(Object[])}. Handled
     * in the background thread.
     * 
     * @param exception
     *            The thrown exception
     */
    protected void onBackgroundException(Exception exception) {
    }

    /**
     * Called when the {@link #doTask(Object[])} method finished executing with
     * no exceptions thrown.
     * 
     * @param result
     *            The result returned from {@link #doTask(Object[])}
     */
    protected void onSuccess(Result result) {
    }

    /**
     * Called when an exception was thrown in {@link #doTask(Object[])}. Handled
     * in the foreground thread.
     * 
     * @param exception
     *            The thrown exception
     */
    protected void onFailure(Exception exception) {
    }
}

class ResultOrException<TResult> {

    /**
     * The possibly thrown exception
     */
    Exception   mException;

    /**
     * The result, if no exception was thrown
     */
    TResult     mResult;

    /**
     * @param exception
     *            The thrown exception
     */
    public ResultOrException(Exception exception) {
        mException = exception;
    }

    /**
     * @param result
     *            The result returned from the method
     */
    public ResultOrException(TResult result) {
        mResult = result;
    }

    /**
     * @return the exception
     */
    public Exception getException() {
        return mException;
    }

    /**
     * @param exception
     *            the exception to set
     */
    public void setException(Exception exception) {
        mException = exception;
    }

    /**
     * @return the result
     */
    public TResult getResult() {
        return mResult;
    }

    /**
     * @param result
     *            the result to set
     */
        public void setResult(TResult result) {
            mResult = result;
        }
    }