luk*_*uku 0 java arrays properties exception
我有一个属性文件,它存储服务器的名称和端口.这些值将在a中使用Enum,以便能够在不触及代码的情况下更改值.
该属性的内容如下所示:
PROD=FTPROD01:1122
Run Code Online (Sandbox Code Playgroud)
问题是我必须拆分服务器和端口号,因为我使用这些值作为方法的参数:
server = properties.getProperty(this.name(), "").split(":")[0];
try {
port = Integer.valueOf(properties.getProperty(this.name(), "").split(":")[1]);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("error");
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,即时捕获ArrayIndexOutOfBoundsException,这是一个运行时异常,以便检测是否缺少第二个值,因为如果属性文件"损坏",程序将崩溃.
这是获取多个值的好方法,还是有更优雅的其他方法?
这是获取多个值的好方法,还是有更优雅的其他方法?
当然 - 不要尝试以无效长度访问数组 - 在执行任何其他操作之前检测它.
String[] bits = properties.getProperty(this.name(), "").split(":");
if (bits.length == 2) {
server = bits[0];
port = Integer.valueOf(bits[1]);
} else {
// Log the corruption or whatever...
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果valueOf抛出a ,这仍然可能失败NumberFormatException.
基本上你应该避免捕获异常,你可以避免挑衅开始.
| 归档时间: |
|
| 查看次数: |
666 次 |
| 最近记录: |