我有以下代码:
public class LoadProperty
{
public static final String property_file_location = System.getProperty("app.vmargs.propertyfile");
public static final String application-startup_mode = System.getProperty("app.vmargs.startupmode");
}
它从“VM arguments”读取并分配给变量。
由于 static final 变量仅在类加载时初始化, 如果有人忘记传递参数,我该如何捕获异常。
截至目前,当我使用“property_file_location”变量时,在以下情况下会遇到异常:
- 如果存在值,但位置错误,则会出现 FileNotFound 异常。
- 如果未正确初始化(值为空),则抛出 NullPointerException。
我只需要在初始化时处理第二种情况。
第二个变量的情况类似。
整个思路是
- 初始化应用程序配置参数。
- 如果初始化成功,继续。
- 如果没有,提醒用户并终止应用程序。
最佳答案
你可以这样捕捉它:
public class LoadProperty
{
public static final String property_file_location;
static {
String myTempValue = MY_DEFAULT_VALUE;
try {
myTempValue = System.getProperty("app.vmargs.propertyfile");
} catch(Exception e) {
myTempValue = MY_DEFAULT_VALUE;
}
property_file_location = myTempValue;
}
}
关于java - 初始化静态最终变量时捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17874171/