堆栈跟踪打印到System.out但不是System.err

时间:2015-12-07 23:48:34

标签: java printstacktrace

我使用的这个课程(JSch)我完全不了解,但我对它的工作原理有一个大概的了解。如果exitStatus不是我想要的,我试图抛出异常。但是,使用

e.printStackTrace() or e.printStackTrace(System.err) //does nothing

e.printStackTrace(System.out) //prints the whole stack trace.

我以前从未见过这个问题,所以我想知道它是不是我不理解导致问题的API,或者Exception堆栈跟踪的工作方式是否有所不同?我有一种感觉,使用apache log4j会起作用,但是我只是为了测试目的而懒得设置它,并且它不会回答为什么会发生这种情况的混乱。

如果有兴趣,这里是代码(我想在exitStatus!= 0时抛出异常):

    Channel channel = null;
    int exitStatus = 1;
    System.out.println(command);
    try {
        channel = session.openChannel("exec");
        ChannelExec channelExec = (ChannelExec) channel;
        channelExec.setPty(true);
        channelExec.setCommand(command);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        InputStream in = channel.getInputStream();
        channel.connect();

        byte[] tmp=new byte[1024];
        int timeout = 0;
        while (true){
            while (in.available() > 0) {
                timeout = 0; // if read success, reset timeout
                int i = in.read(tmp, 0, 1024);
                if (i < 0)break;
                String status = new String(tmp, 0, i);
                /*System.out.println(status);*/
                if (status.toLowerCase().contains("incorrect password")) {
                    channel.disconnect();
                } else if (status.toLowerCase().contains("password")) {
                    OutputStream out = channel.getOutputStream();
                    out.write(args);
                    out.write('\n');
                    out.close();
                }
            }
            if (channel.isClosed()){
                exitStatus = channel.getExitStatus();
                break;
            }
            try { Thread.sleep(1000); } catch (Exception ee) { ee.printStackTrace(); }
            // nothing reads for 4 turns but stream is not closing, probably waiting for user input so exit
            if (timeout++ > 5) { 
                break;
            }
        }
    } catch (IOException ioe) {
        throw new ApplicationException(ioe);
    } catch (JSchException je) { 
        throw new ApplicationException("Could not create an exec channel for SSH. ", je);
    } finally {
        if (channel.isConnected()) channel.disconnect();
    }

  //if (exitStatus != 0) throw new MyCustomException(errormsg) 

感谢。

0 个答案:

没有答案