【问题标题】:Try Catch vs If Else尝试 Catch 与 If Else
【发布时间】:2012-07-05 13:19:44
【问题描述】:

以下哪个代码更好实现

public string myfunc(JSONArray funcargs){

    int ctxHandle;
    String StringParam=null;
    JSONObject jObj=null;

    try {
        ctxHandle = funcargs.getInt(2);
        if(funcargs.length() == 4) {
            try {
                StringParam = funcargs.getString(3);
            } catch (JSONException jsonEx) {
                jObj = funcargs.getJSONObject(3);
            }
        }
    } catch (JSONException jsonEx) {
        SendJS = "javascript:" + FailureCallBack + "('" + jsonEx.getMessage() + "')"; 
        sendJavascript(SendJS);
        return null;
    }

    //This will return an integer
    ret_val = get_data(ctxHandle);
    SendJS = "javascript:" + SuccessCallBack + "('" + Integer.toString(ret_val);
    if(StringParam != null)
        SendJS  += "','" + StringParam + "')";
    else if(jObj != null)
        SendJS  += "','" + jObj + "')";
    else 
        SendJS  += "')";

    sendJavascript(SendJS);
    return null;
}

public string myfunc(JSONArray funcargs){

    int ctxHandle;
    String StringParam=null;
    JSONObject jObj=null;

    try{
        ctxHandle = funcargs.getInt(2);
        //This will return an integer
        ret_val = get_data(ctxHandle);
        SendJS = "javascript:" + SuccessCallBack + "('" + Integer.toString(ret_val);
        if(funcargs.length() == 4) {
            try {
                StringParam = funcargs.getString(3);
                SendJS  += "','" + StringParam + "')";
            } catch (JSONException jsonEx) {
                jObj = funcargs.getJSONObject(3);
                SendJS  += "','" + jObj + "')";
            }
            SendJS  += "')";
        }
    } catch (JSONException jsonEx) {
        SendJS = "javascript:" + FailureCallBack + "('" + jsonEx.getMessage() + "')"; 
    }

    sendJavascript(SendJS);
    return null;                        
}

个人来自Java if vs. try/catch overhead 线程我知道try/catch 应该仅用于您不确定结果并且可以处理异常但 if else if can be saved 参数会产生一些疑问,尽管将try catch 块中的整个代码对我来说毫无意义。

在这方面需要帮助。

【问题讨论】:

  • 你能从代码中删除不相关的部分吗?并指出不同的部分?
  • @Thilo 整个想法是从整体上分析函数,而不是仅仅看到它的点点滴滴,它只有 15 行代码。所以我发布了:)

标签: java


【解决方案1】:

通常我们在预期会出现错误的地方使用 try catch。例如,您要将一个数字与另一个数字相除,结果为零,肯定会引发错误。在那里我们将使用 try catch。

那是为了捕捉运行时错误,我们使用try catch。

不是必须在所有代码中都使用 try catch,但是使用 try catch 会减少出现异常的机会。

【讨论】:

    【解决方案2】:

    代码没有做同样的事情,但如果你修复了第二个例子,我会说它更好,因为你将相关代码放在一起。

    但是,我建议你应该做你认为更清楚的事情,因为第一个例子可能是正确的,它可能是你更好的选择。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-21
      • 2017-04-07
      • 1970-01-01
      • 2015-09-13
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多