2

I am trying to merge 2 simple programs I have made to one .jar. I packed both .jars into a new one and used Runtime.getRuntime().exec method to execute them.

Code:

public class main {
  public static void main(String[] args) {
    try {
      Runtime.getRuntime().exec("cmd /c proj1.jar");
    } catch(Exception exce){ 
      /*handle exception*/
      try {
        Runtime.getRuntime().exec("cmd /c proj2.jar");
      } catch(Exception exc){
        /*handle exception*/

      }
    }
  }
}

The problem is that only proj1.jar is executed and proj2.jar doesn't run. I am new to java and don't know why this happens. How do I fix this? I want both files to be executed.

2
  • Are you sure if the first one is not throwing exception? Can you try printing the stack trace! Commented Jun 19, 2012 at 17:26
  • Are you getting some exceptions? Commented Jun 19, 2012 at 17:28

1 Answer 1

7

Your problem is that your second file is ONLY executed if the first throws an exeception. You're looking for this:

public class main {
  public static void main(String[] args) {
    try {
      Runtime.getRuntime().exec("cmd /c proj1.jar");
      Runtime.getRuntime().exec("cmd /c proj2.jar");
    } catch(Exception exce){ 
      /*handle exception*/
    }
  }
}

Or, if you absolutely must handle the exceptions separately, this:

public class main {
  public static void main(String[] args) {
    try {
      Runtime.getRuntime().exec("cmd /c proj1.jar");
    } catch(Exception exce){ 
      /*handle exception*/
    }

    try {
      Runtime.getRuntime().exec("cmd /c proj2.jar");
    } catch (Exception e) {
      //handle the exception
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Your edit of the original code changes everything ! I didn't even see the imbrication...
This is why code formatting is actually super important. It establishes clarity! Problems just fall away!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.