我有这段代码:
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
的意思,事实上 - 它将始终被初始化(因为程序将在无法初始化时退出)。我必须尝试抓住那里,因为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]
你知道我能做些什么来解决这个问题吗?谢谢!
如果程序无法初始化,编译器不会知道该程序将退出。只需在try中移动其余代码即可。
public static void main (String[] args) {
try {
Config c = new Config();
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();
} catch (Exception e) {
System.err.println("Error while parsing/reading file: " + e.getMessage());
System.exit(-1);
}
}
System.exit(-1)
不保证您的程序会停止。如果您有某种关闭挂钩,或者如果您正处于流操作的中间,则可以阻止它。因此编译器抛出错误。
你可能想让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();
“事实上 - 它将始终被初始化(因为程序将在无法初始化时退出)。”
编译器如何知道这一点?此外,如果它将始终初始化,那么为什么要使用try-catch
呢?你的逻辑有一个缺陷。
您可以将其余代码移到try
block中。那会有用。