gpt4 book ai didi

java - getenv() 的异常处理程序

转载 作者:行者123 更新时间:2023-12-02 11:13:25 28 4
gpt4 key购买 nike

如何处理此类行代码的 NullPointerExceptionSecurityException:

public final static String PROJECT_DIR = System.getenv().get("HOME") + "/Projects/MyTestProject";

try/catch 包装就足够了?如果是这样,我该如何区分它是 NullPointerExceptionSecurityException

如果 getenv() 不可用或其他原因,是否有任何最佳实践将其存储在属性中?

最佳答案

在类初始值设定项中初始化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);
}
}

关于java - getenv() 的异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452939/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com