java try catch并返回

时间:2011-10-20 19:22:08

标签: java json httpclient

我在java中有一个小函数来执行HTTP POST,并返回一个JSON对象。此函数返回JSON对象。

public JSONObject send_data(ArrayList<NameValuePair> params){
    JSONObject response;
    try {
        response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
        return response;
    } catch(Exception e) {
        // do smthng
    }
}

这显示了函数必须返回JSONObject的错误。我如何使它工作?当出现错误时我无法发送JSONObject,是吗?发送一个空白的jsonobject

是没用的

6 个答案:

答案 0 :(得分:10)

这是因为如果一切顺利,您只返回JSONObject。但是,如果抛出异常,您将进入catch块并且不从函数返回任何内容。

你需要

  • 在catch块中返回一些内容。例如:

    //...
    catch(Exception e) {
        return null;
    }
    //...
    
  • 在catch块之后返回一些东西。例如:

    //...
    catch (Exception e) {
        //You should probably at least log a message here but we'll ignore that for brevity.
    }
    return null;
    
  • 从方法中抛出异常(如果选择此选项,则需要将throws添加到send_data的声明中。

    public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
        return new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
    }
    

答案 1 :(得分:2)

您可以将其更改为:

public JSONObject send_data(ArrayList<NameValuePair> params){
    JSONObject response = null;
    try {
        response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
    } catch(Exception e) {
        // do smthng
    }

    return response;
}

答案 2 :(得分:0)

通过该函数的路径不会返回任何内容;编译器不喜欢这样。

您可以将其更改为

catch(Exception e) {
    // do smthng
    return null; <-- added line
}
or put the return null (or some reasonable default value) after the exception block.

答案 3 :(得分:0)

即使在错误的情况下也可以返回'某事'。 查看JSend,了解标准化答案的方法 - http://labs.omniti.com/labs/jsend

在我看来,返回一个错误的json对象并在客户端处理它然后完全依赖于HTTP错误代码是最容易的,因为并非所有框架都能处理这些错误代码。

答案 4 :(得分:0)

我更喜欢一个入口和一个出口。这样的事情对我来说似乎很合理:

public JSONObject send_data(ArrayList<NameValuePair> params)
{
    JSONObject returnValue;
    try
    {
        returnValue = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
    }
    catch (Exception e)
    {
        returnValue = new JSONObject(); // empty json object .
        // returnValue = null; // null if you like.
    }

    return returnValue;
}

答案 5 :(得分:0)

send_data()方法应该抛出异常,以便调用send_data()的代码可以控制它想要处理异常的方式。

public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
  JSONObject response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
  return response;
}

public void someOtherMethod(){
  try{
    JSONObject response = sendData(...);
    //...
  } catch (Exception e){
    //do something like print an error message
    System.out.println("Error sending request: " + e.getMessage());
  }
}
相关问题