它是在Java中可以接受的做法嵌套的try / catch语句?例如 [英] Is it acceptable practice in Java to nest try/catch statements? For example

查看:180
本文介绍了它是在Java中可以接受的做法嵌套的try / catch语句?例如的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从创建Android的一个IP地址的值传递(使用捆绑),如果失败,我使用的是硬codeD默认IP地址创建。如果失败的话,我退出应用程序。

I am trying to create an IP address in Android from a passed in value (using Bundle), and if it fails I'm creating it using a default IP address that is hard coded. If that fails then I am exiting the app.

我想知道,如果其确定嵌套的try / catch是因为我在这里做,或是否有更好的方法是。

What I'd like to know is if its ok to nest try/catch's as I have done here, or is there a better way.

    try {
        // serverSettings is the Bundle name that was passed in.
        ipAddress = InetAddress.getByName(serverSettings.getString("serverIp"));
    } catch (UnknownHostException e) {
        Log.e("ERROR:", "IOException: Failed to create IP, trying default");
        try {
            // DEFAULT_IP is the hard-coded default fall-back address
            ipAddress = InetAddress.getByName(DEFAULT_IP);
        } catch (UnknownHostException e1) {
            Log.e("ERROR:", "IOException: Total fail, exiting");
            e1.printStackTrace();
            finish();
        }
    }

干杯

史蒂夫

推荐答案

这是合法的Java。它看起来笨重给我,我可能会采取不同的方式,但它是有效的和作品。

It's legal Java. It looks clunky to me, and I'd probably do it differently, but it's valid and works.

下面就是我会做到这一点:

Here's how I'd do it:

public InetAddress getServerAddress() {
    for (String address : new String[] {serverSettings.getString("serverIp"), DEFAULT_IP}) {
        try {
            return InetAddress.getByName(address);
        } catch (UnknownHostException e) {
            Log.e("ERROR:", "Cannot resolve " + address);
        }
    }
    Log.e("ERROR:", "Total fail, exiting");
    finish();
    return null;    // not reached
}

这篇关于它是在Java中可以接受的做法嵌套的try / catch语句?例如的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆