简体   繁体   中英

Initializing Java variable

I am starting a process. And later I want to be able to destroy the said process then start it again.

Process myProcess;

try {
    myProcess = Runtime.getRuntime().exec(pathToMyProgram);
} catch (IOException e) {
    e.printStackTrace();
}

Then I do stuff. And later:

try {
    myProcess.destroy();
    myProcess = Runtime.getRuntime().exec(pathToMyProgram);
} catch (IOException e) {
    e.printStackTrace();
}

The problem is at the line

myProcess.destroy();

There is an error because myProcess can be uninitialized at this point. Also I can't do something like:

myProcess = new Process();

I know I could solve this by putting everything in a big try{} statement but is there another way ?

EDIT: I cannot do the null check either, the error is: the process might not be initialized.

But thanks to you I then tried to do Process myProcess = null; and now it works ! Thank you and sorry for the bad question.

I'm removing the process tag for relevance. And edited title.

Doing so solved my problem. Sorry for the newb question.

Process myProcess = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM