java try catch并返回

Ami*_*mit 2 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jac*_*nds 10

这是因为JSONObject如果一切顺利,你只会回来.但是,如果抛出异常,您将进入该catch块而不返回该函数中的任何内容.

你需要

  • 在catch块中返回一些东西.例如:

    //...
    catch(Exception e) {
        return null;
    }
    //...
    
    Run Code Online (Sandbox Code Playgroud)
  • 在阻止块之后返回一些东西.例如:

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

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