Run a java program through java code

147 Views Asked by At

I am working in Linux/Ubuntu. I want to run a process in through my java code, which looks like below

ProcessBuilder pb = new ProcessBuilder("/usr/lib/flume-ng/bin/flume-ng", 
                                       "agent", 
                                       "-f", 
                                       "/home/c4/Flume/New/ClientAgent.config",
                                       "-n", 
                                       "clientAgent");
    pb.start();

But i get unreported exception java.io.IOException; must be caught or declared to be thrown pb.start(); as error output. Please tell me how i can run my process. Thanks.

2

There are 2 best solutions below

0
On

It's telling you the start() method could throw an Exception, and you have to deal with it. You can either:

  1. catch it and log it or otherwise handle it, or
  2. declare your method as possibly throwing this exception, and let a method higher up the stack handle it (using these two options)

The Exception object is checked, which means the compiler is concerned with it, and you need to be too (however much of a pain that is). Other exceptions are unchecked, and this means you don't have to worry. The compiler won't worry either (e.g. OutOfMemoryError - be aware that I'm mixing some exception terminology here, since it's a little convoluted).

0
On

Since, IOException is a checked exception you need to either catch it

try {
    pb.start();
} catch (IOException e) {
    e.printStackTrace();
}

or throw it with the enclosing method declared to do so.

public void yourMethod() throws IOException {