如何为这种行代码处理NullPointerException
和SecurityException
:
public final static String PROJECT_DIR = System.getenv().get("HOME") + "/Projects/MyTestProject";
用try/catch
包裹它就足够了吗?如果是这样,我将如何区别NullPointerException
或SecurityException
?
如果getenv()
不可用或其他什么原因,是否还有将其存储在属性中的最佳做法?
答案 0 :(得分:1)
初始化类初始值设定项中的final static String
。抛出描述问题的新异常(未设置,不允许)。例如:
public final static String PROJECT_DIR;
static {
try {
Map<String, String> env = System.getenv();
if (!env.contains("HOME")) {
throw new AssertionError("HOME not set as environment variable");
}
PROJECT_DIR = env.get("HOME") + "/Projects/MyTestProject";
} catch (SecurityException e) {
throw new AssertionError("Security policy doesn't allow access to system environment", e);
}
}
答案 1 :(得分:0)
这会抛出NullPointerExceptions和SecurityExceptions:
{{1}}