I have a class (named C) to check the structure of JSON and if the structure is wrong, it will throws exception. That class will be called from class B. I can use try catch
in class B. But actually, class B is called by class A, which provide callback to class B. How do I send exception from class C which is called by class B to the callback (OnFinishListener
) in class A? I want to provide try catch
in the callback declaration in class A, not class 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");
}
}
}