getenv()

时间:2018-05-21 16:24:24

标签: java exception exception-handling nullpointerexception securityexception

如何为这种行代码处理NullPointerExceptionSecurityException

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

try/catch包裹它就足够了吗?如果是这样,我将如何区别NullPointerExceptionSecurityException

如果getenv()不可用或其他什么原因,是否还有将其存储在属性中的最佳做法?

2 个答案:

答案 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}}