getenv() 的异常处理程序
Exceptions handler for getenv()
如何处理 NullPointerException
和 SecurityException
那种线路代码:
public final static String PROJECT_DIR = System.getenv().get("HOME") + "/Projects/MyTestProject";
只用try/catch
包裹就可以了吗?如果是这样,我怎么能不同它将是 NullPointerException
或 SecurityException
?
如果 getenv()
不可用或其他原因,是否还有将其存储在属性中的最佳做法?
在 class 初始化器中初始化 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);
}
}
这会抛出 NullPointerExceptions 和 SecurityExceptions:
public static void main(String[] args) throws Exception {
System.out.println("System.getenv("HOME") = ");
System.out.println(System.getenv("HOME"));
如何处理 NullPointerException
和 SecurityException
那种线路代码:
public final static String PROJECT_DIR = System.getenv().get("HOME") + "/Projects/MyTestProject";
只用try/catch
包裹就可以了吗?如果是这样,我怎么能不同它将是 NullPointerException
或 SecurityException
?
如果 getenv()
不可用或其他原因,是否还有将其存储在属性中的最佳做法?
在 class 初始化器中初始化 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);
}
}
这会抛出 NullPointerExceptions 和 SecurityExceptions:
public static void main(String[] args) throws Exception {
System.out.println("System.getenv("HOME") = ");
System.out.println(System.getenv("HOME"));