如何在异常后执行命令

时间:2016-10-18 20:58:05

标签: java

我有一个带有一些系统命令的2d数组someArray。假设我有这些命令 -

  • ls
  • lol(无效命令)
  • pwd

第二个命令将触发IOException,第三个命令不会被执行。如何确保最后一个命令将被执行而不管任何异常?有什么建议吗?

              for ( int i = 0; i < someArray.length; i++ ) {
                 try{
                    ProcessBuilder pb = new ProcessBuilder(someArray[index]);
                    pb.redirectErrorStream(true);
                    Process process = pb.start();

                    InputStream is = process.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);

                    String line;
                    while ( (line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    br.close();
                }catch(IOException e){
                    System.err.println( "Command not found" );
                }
             }

1 个答案:

答案 0 :(得分:-1)

而不是在catch中使用IOException而是使用通用类Exception,它将捕获任何类型的Exception抛出

    for ( int i = 0; i < someArray.length; i++ ) {
        try{
           ProcessBuilder pb = new ProcessBuilder(someArray[i]);
           pb.redirectErrorStream(true);
           Process process = pb.start();

           InputStream is = process.getInputStream();
           InputStreamReader isr = new InputStreamReader(is);
           BufferedReader br = new BufferedReader(isr);

           String line;
           while ( (line = br.readLine()) != null) {
               System.out.println(line);
           }
           br.close();
       } catch (IOException e) {
           System.err.println( "Command not found" );
       } catch (Exception e) {
           System.err.println("Unexpected Exception caught to continue other commands");
           e.printStackTrace();
       }
    }

编辑:已修复以报告意外错误