2011-04-28 54 views
2

我有以下的代碼框架異常處理冒險

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

您確定異常正在引發您捕捉的同一線程上嗎? – forsvarir 2011-04-28 12:04:24

+0

我這麼認爲。但我不確定。 – hari 2011-04-29 09:49:39

回答

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... 
7

不,IllegalBlockingModeExceptionException(幾個級別下)的子類,所以你正在捕捉正確的類型。請參閱javadoc

但是,它可能是異常從另一個線程拋出,在這種情況下,您不會在您的try/catch塊中看到它。拋出異常的線程是"ExpectJ Stream Piper"

+0

但是,爲什麼Stream Piper會拋出一個異常?因爲當我調用interact()時,我能夠成功地與系統交互。它只會在調用該方法後不進行交互時在運行時引發這樣的異常。好!如果所有異常都是從不同的線程拋出,我的方法是什麼?我從來沒有遇到過這種情況。 – hari 2011-04-29 08:49:39

1

有沒有運氣試圖擺脫,而不是相互作用的exception.So的,()我們可以使用的BufferedReader採取輸入一個字符串,該字符串傳遞到的send()。這樣更方便。

+0

你有可能提供示例代碼嗎?我面臨同樣的問題,StreamPiper在bytes_read = inputStream.read(buffer)上失敗; – Martin 2011-08-19 14:20:07