2017-01-10 17 views
0

你好下面我分享我的代碼: 問題是它沒有任何錯誤,但我得到「異常JsonException永遠不會拋出相應的嘗試語句的主體」在服務器中。JSONException從來沒有被拋出在相應的try語句,不同的環境

當我在以下兩種方法中添加「throws JSONException」的聲明時,問題就解決了,但實際上我不想這樣做。這可能是什麼原因?

private JSONArray convertStringToJsonArray(String source)throws JSONException { 
    return new JSONArray(source); 
} 

private JSONObject getElementIndexAt(JSONArray jsonArray, int index)throws JSONException { 
    return jsonArray.getJSONObject(index); 
} 

public class JsonModifier { 

public String getElementIndexAt(String source, int index){ 
    String output; 

    try 
    { 
     JSONArray jsonArray = convertStringToJsonArray(source); 
     JSONObject jsonObject = getElementIndexAt(jsonArray, index); 
     output = convertJsonToString(jsonObject); 
    } 
    catch(JSONException ex) 
    { 
     log.error("Page not found, exception: " + ex.getMessage()); 
     output = "Page not found, exception: " + ex.getMessage(); 
    } 

    return output; 
} 

private JSONArray convertStringToJsonArray(String source) { 
    return new JSONArray(source); 
} 

private JSONObject getElementIndexAt(JSONArray jsonArray, int index) { 
    return jsonArray.getJSONObject(index); 
} 

private String convertJsonToString(JSONObject jsonObject){ 
    return jsonObject.toString(); 
} 

}

回答

0

正如documentation,getJSONObject和構造函數拋出異常說。所以,如果你不用try/catch包圍這些函數,你必須向上拋出這個異常。

注意:您在自己的函數中使用try/catch,這就是您的解決方案的原因。

希望這會有所幫助:)

相關問題