异常处理冒险

时间:2011-04-28 12:01:11

标签: java exception-handling try-catch

我有以下代码骨架

try {    
...    
...    
sysout("Please provide an input: ");
Thread.sleep(10000); //10 secs time given to the user to give the input. If the user doesn't enter the input it is throwing the exception, which is not being handled (with the custom message)
interact();  //This is a method that belongs to **expectj.Spawn** class
...
...    
} catch (Exception e) {

    System.out.println("You have not given any input!Please try again!");

}

但我仍然得到以下输出 -

Exception in thread "ExpectJ Stream Piper" java.nio.channels.IllegalBlockingModeException

at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:39)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:92)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:86)
at java.io.InputStream.read(InputStream.java:85)
at expectj.StreamPiper.run(StreamPiper.java:134)

我需要处理其他任何异常吗?

3 个答案:

答案 0 :(得分:7)

不,IllegalBlockingModeExceptionException的子类(有几个级别),所以你正在捕捉正确的类型。请参阅javadoc

但是,可能是异常是从另一个线程抛出的,在这种情况下你不会在try / catch块中看到它。抛出异常的线程是"ExpectJ Stream Piper"

答案 1 :(得分:1)

试图摆脱异常没有运气。所以,我们可以使用 bufferedreader 来将输入转换为字符串并传递字符串转换为 send()。那更方便。

答案 2 :(得分:0)

我认为扫描仪比BufferedReader好。

ExpectJ exp = new ExpectJ(10);
String cmd = "sh test.sh";
Scanner sc = new Scanner();
Spawn s = exp.spawn(cmd);
s.expect("Name");
String answer1 = sc.next();
s.send(answer1 + "\n);
s.expect("Password");
String answer2 = sc.next();
s.send(answer2+"\n");
.
.
.
//and so on...