我有一个类(名为C)来检查JSON的结构,如果结构错误,它将抛出异常。该类将从类B中调用。我可以在类B中使用try catch
。实际上,类B由类A调用,它提供对类B的回调。如何从调用类C调用异常通过B类到A类的回调(OnFinishListener
)?我想在A类的回调声明中提供try catch
,而不是B类。
public class A {
B b = new B();
b.getResponseFromServer(new B.OnFinishListener {
@Override
public void onFinish(Object response) {
});
}
public class B {
public static interface OnFinishListener {
void onFinish(Object response);
}
//other code
public void getResponseFromServer(OnFinishListener onFinishListener) {
Response.Listener<JSONObject> listener = new Response.Listener<>() {
@Override
public void onResponse(JSONObject response) {
try {
onFinishListener.onFinish(C.someMethod(response);
catch (JSONException e) {
Log.e("Error", e.getMessage());
}
}
}
//do some Volley tasks
}
}
public class C {
public static Object someMethod(JSONObject json) throws JSONException {
if (json.has("something")) {
//return something
} else {
throw new JSONException("Error");
}
}
}
答案 0 :(得分:4)
我得到了解决方案。我只需要在我的接口(onException)中添加一个方法,并在catch(Exception)
上将此异常传递给该接口。
public class A {
B b = new B();
b.getResponseFromServer(new B.OnFinishListener {
@Override
public void onFinish(Object response) {}
@Override
public void onException(JSONException response) {}
);
}
public class B {
public static interface OnFinishListener {
void onFinish(Object response);
void onException(JSONException e);
}
//other code
public void getResponseFromServer(OnFinishListener onFinishListener) {
Response.Listener<JSONObject> listener = new Response.Listener<>() {
@Override
public void onResponse(JSONObject response) {
try {
onFinishListener.onFinish(C.someMethod(response);
catch (JSONException e) {
onFinishListener.onException(e);
}
}
}
//do some Volley tasks
}
}
&#13;
答案 1 :(得分:-1)
Try ur code to put in Try Catch...
try {
if (json.has("something")) {
} else {
}
}catch (JSONException e) {
e.printStackTrace();
}