gpt4 book ai didi

java - 变量 c 可能尚未初始化

转载 作者:行者123 更新时间:2023-12-01 07:00:48 24 4
gpt4 key购买 nike

我有这段代码:

public static void main (String[] args) {
Config c;// = null;
try {
c = new Config();
} catch (Exception e) {
System.err.println("Error while parsing/reading file: " + e.getMessage());
System.exit(-1);
}
final NetworkReporter np = new NetworkReporter(c.getValues().serverIP, c.getValues().serverPort, (short)(c.getValues().checkInterval * c.getValues().checksPerReport));
IdleChecker idleChecker = new IdleChecker(c.getValues().checkInterval, c.getValues().checksPerReport, c.getValues().idleSensitivity, new IdleChecker.reportFunction() {
public void report() {
np.report();
}
});
idleChecker.start();
}

当我编译这段代码时,我得到:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project FanstisTime: Compilation failure
[ERROR] /home/amitg/Programming/Projects/FantisTime/FantisTime/src/main/java/com/amitg/fantistimeclient/Client.java:[13,54] variable c might not have been initialized

我确实明白什么variable c might not have been initialize意味着,事实上 - 它总是会被初始化(因为如果无法初始化程序将退出)。我必须在那里 try catch ,因为 new Config()抛出一些异常。我尝试使用 Config c = null;在那里,它给了我这个:

[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project FanstisTime: An exception occured while executing the Java class. null: NullPointerException -> [Help 1]

你知道我能做什么来解决这个问题吗?谢谢!

最佳答案

System.exit(-1)

不保证您的程序会停止。如果您有某种关闭 Hook ,或者如果您正在进行流操作,则可以防止这种情况发生。因此编译器会抛出错误。

您可能想让Exception转义当前层。

Config c;

try {
c = new Config();
} catch (final Exception e) {
System.err.println("Error while parsing/reading file: " + e.getMessage());
throw new YourCustomRuntimeException(e);
}

c.whatever();

关于java - 变量 c 可能尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227901/

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