Search code examples
javaandroidparse-platformparse-cloud-code

Cloud Code function: try-catch did not catch ClassCastException


Here is a Cloud Code function:

Parse.Cloud.define('testQuery', function(request, response) {
    response.success('Test String');
});

I call this function by Parse Android SDK:

try {
    HashMap<String, Object> params = new HashMap<>();

    ParseCloud.callFunctionInBackground("testQuery", params, new FunctionCallback<ArrayList<String>>() {
        @Override
        public void done(ArrayList<String> results, ParseException e) {
            Log.d("Test", "Done");
        }
    });
} catch (ClassCastException e) {
    Log.d("Test", "Exception: " + e.toString());
}

I understand that I am casting from String to ArrayList, which will cause ClassCastException. So I add a try-catch, but the app still crash. What is the reason that I can't catch the Exception? Thanks.

E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.honestly, PID: 23014
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList
    at app.myapp.MyActivity$1.done(MyActivity.java:189)
    at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:115)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5234)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

Solution

  • As the name ParseCloud.callFunctionInBackground suggest the callback parameter is executed asynchronously. The try catch is entered, the ParseCloud.callFunctionInBackground and callback stored, the try catch is exited, then at some point in time the callback function is executed.

    One way to solve it is to accept a String and then convert it to array list:

    ParseCloud.callFunctionInBackground("testQuery", params, new FunctionCallback<String>() {
        @Override
        public void done(String results, ParseException e) {
            try { 
                List<String> result = convertToList(results);
    
            }catch(Exception ex){
                Log.e("Test", "Problem " + ex);
            }
            Log.d("Test", "Done");
        }
    });