Click here to Skip to main content
15,887,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've made a client/Server app using TCP sockets, but clients stuck too often and they throw "Connection timed out" while reading for new messages from the Server.
On both apps im using this:
Java
try{
   do{
     message=(String) input.readLine();

     System.out.println(message);

   }while(!message.equals("Disconnect"));
 }catch (IOException e) {
    System.out.println(e.getMessage());
 }

But at examples i've seen, the do these:
Java
do{
  try{
     message=(String) input.readLine();

     System.out.println(message);

  }catch (IOException e) {
     System.out.println(e.getMessage());
  }
}while(!message.equals("Disconnect"));


Is there any major difference to use "try" out of the "do{}while" than using "try" inside the "do{}while"?

What I have tried:

Until now i have tested both ways but i didnt managed to recreate the error.
Posted
Updated 31-Jul-17 3:25am
Comments
Jochen Arndt 31-Jul-17 9:34am    
There is no great difference but the second is the usual option (catch exceptions for the code portion that may throw).

However, in your example the second option would not leave the loop upon errors while the first does.

But there is no relation to network timeout errors. Solving those requires knowing how your communication works.

1 solution

Yes, there is a difference.

In the first code block, when there's an error in the try block, you exit the do-while loop and go into catch. readLine does not get called anymore, because the code that goes after the catch block gets executed now.

In the second code block, when there's an error in the try block, you do not exit the do-while loop (because try-catch is inside the loop). So, in case of an error, after the code in catch is executed, the loop continues to run and readLine gets executed again.
 
Share this answer
 
Comments
Member 13337752 31-Jul-17 9:33am    
Could be this the reason then for the "Connection timed out" error, which appears so othen?
Thomas Daniels 31-Jul-17 9:44am    
No. The only practical difference is whether the client will continue reading after an error.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900