如何在 try/catch 块中重构此 If/else 语句?

How to refactor this If/else statement in a try/catch block?

我想知道是否有更好的方法来编写这段代码:

private void getLatitudeAndLongitudeFromZipcode() {
        String zipcode = mSharedPreferences.getString("Zipcode", "");

        try {
            List<Address> address = geocoder.getFromLocationName(zipcode, 1);
            if ((address != null ? address.size() : 0) > 0) {
                Address first = address.get(0);
                mLatitude = first.getLatitude();
                mLongitude = first.getLongitude();
                mCurrentLocationName = getLocationAsName();
                mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
                        .apply();
                mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
                        .apply();
            } else {
                getOldZipcodeLocation();//duplicate method call
            }
        } catch (IOException e) {
            getOldZipcodeLocation();//duplicate method call
            e.printStackTrace();
        }
    } 

基本想法是,如果他们没有互联网并且抛出异常,我想从存储中获取旧坐标。但是,如果它们当前所在的位置没有给它们坐标,我也想获取旧坐标。例如,如果地理编码器 returns 为空。困扰我的是 else 块和 catch 块中的重复方法调用。有什么方法可以使这段代码更清晰?我也会采纳任何其他提示!

是的,您可以,首先通过 IOException 分别获得 address,然后在您的 if..else 语句中使用 address。就是这样。

 private void getLatitudeAndLongitudeFromZipcode() {

    String zipcode = mSharedPreferences.getString("Zipcode", "");
    List<Address> address = null;
    try {
        address = new Geocoder(this).getFromLocationName(zipcode, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if ((address != null ? address.size() : 0) > 0) {
        Address first = address.get(0);
        mLatitude = first.getLatitude();
        mLongitude = first.getLongitude();
        mCurrentLocationName = getLocationAsName();
        mSharedPreferences.edit().putLong("oldLat", Double.doubleToRawLongBits(mLatitude))
                .apply();
        mSharedPreferences.edit().putLong("oldLong", Double.doubleToRawLongBits(mLongitude))
                .apply();
    } else {
        getOldZipcodeLocation();

    }
}