我想捕獲doInBackground中線程的異常,並在onPostExcecute中輸出錯誤消息。問題是我沒有onPostExecute中的Throwable對象。如何在非UI線程中捕獲異常和在UI線程中打印錯誤消息?阿倫的回答後AsyncTask的捕獲異常。需要思考
public class TestTask extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(final Void... params) {
try {
...
return listOfString;
} catch(SomeCustomException e) {
...
return null;
}
}
@Override
protected void onPostExecute(final List<String> result) {
if(result == null) {
// print the error of the Throwable "e".
// The problem is I don't have the Throwable object here! So I can't check the type of exception.
}
}
}
更新:
這是我的AsyncTask包裝類。它打算在doInBackground中處理異常,但我找不到一個好的解決方案。
public abstract class AbstractWorkerTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result>
implements Workable {
protected OnPreExecuteListener onPreExecuteListener;
protected OnPostExecuteListener<Result> onPostExecuteListener;
protected ExceptionHappenedListener exceptionHappendedListener;
private boolean working;
@Override
protected void onPreExecute() {
if (onPreExecuteListener != null) {
onPreExecuteListener.onPreExecute();
}
working = true;
}
@Override
protected void onPostExecute(final Result result) {
working = false;
if(/* .........*/) {
exceptionHappendedListener.exceptionHappended(e);
}
if (onPostExecuteListener != null) {
onPostExecuteListener.onPostExecute(result);
}
}
@Override
public boolean isWorking() {
return working;
}
public void setOnPreExecuteListener(final OnPreExecuteListener onPreExecuteListener) {
this.onPreExecuteListener = onPreExecuteListener;
}
public void setOnPostExecuteListener(final OnPostExecuteListener<Result> onPostExecuteListener) {
this.onPostExecuteListener = onPostExecuteListener;
}
public void setExceptionHappendedListener(final ExceptionHappenedListener exceptionHappendedListener) {
this.exceptionHappendedListener = exceptionHappendedListener;
}
public interface OnPreExecuteListener {
void onPreExecute();
}
public interface OnPostExecuteListener<Result> {
void onPostExecute(final Result result);
}
public interface ExceptionHappenedListener {
void exceptionHappended(Exception e);
}
}
可以實現某種回調的設置和獲取錯誤。 –
我試過了,但是我不能在doInBackground中返回Exception和List。怎麼做? –
Emerald214
嘗試從'doInBackground()'的'catch'返回'e.toString()'而不是'null' ... – GAMA