我正在尝试根据传入的值(使用 Bundle)在 Android 中创建 IP 地址,如果失败,我将使用硬编码的默认 IP 地址创建它。如果失败,我将退出该应用。
我想知道的是,是否可以像我在这里所做的那样嵌套 try/catch,或者是否有更好的方法。
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。它对我来说看起来很笨重,我可能会以不同的方式来做,但它是有效的并且有效。
这是我的做法:
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 - 在 Java 中嵌套 try/catch 语句是否可以接受?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774505/