unreachable statement try { error


im trying to 'mash' a server and client together, with not much success, the code looks as follows:

import java.net.*;
import java.io.*;

public class server2

static final int LISTENING_PORT = 4130;
      public static void main(String[] args) {
         File folder;        // The directory from which the
                                //    gets the files that it serves.
         ServerSocket listener; // Listens for connection requests.
         Socket connection;     // A socket for communicating with
                                //                a client.
        PrintWriter outgoing;
         TextReader incoming;  

         String command;       // Command to send to the server.
        //server element below
         /* Get the directory name from the command line, and make
            it into a file object.  Check that the file exists and
            is in fact a directory. */
             folder = new File("stuff");

         if ( ! folder.exists() ) {
            System.out.println("Folder: " + folder +" -- does not exist.");
         if (! folder.isDirectory() ) {
            System.out.println("The file you require is not a folder.");
         /* Listen for connection requests from clients.  For
            each connection, create a separate Thread of type
            ConnectionHandler to process it.  The ConnectionHandler
            class is defined below.  The server runs until the
            program is terminated, for example by a CONTROL-C. */
         try {
            listener = new ServerSocket(LISTENING_PORT);
            System.out.println("\nServer listening on port " + LISTENING_PORT);
            while (true) {
               connection = listener.accept();
         catch (Exception e) {
            System.out.println("Server shut down unexpectedly.");
            System.out.println("Error:  " + e);
         //client element

         /* Make the connection and open streams for communication.
            Send the command to the server.  If something fails
            during this process, print an error message and end. */
         try {
            connection = new Socket( "localhost", LISTENING_PORT );
            incoming = new TextReader( connection.getInputStream() );
            outgoing = new PrintWriter( connection.getOutputStream() );
         catch (Exception e) {
                 "Can't make connection to server at localhost.");
            System.out.println("Error:  " + e);
             if (args.length == 0)
            command = "list";
            command = "get " + args[0];      
         /* Read and process the server's response to the command. */
         try {
            if (args.length == 0) {
                  // The command was "filelist".  Read and display lines
                  // from the server until the end-of-stream is reached.
               System.out.println("File list from server:");
               while (incoming.eof() == false) {
                  String line = incoming.getln();
                  System.out.println("   " + line);
            else {
                  // The command was "get <file-name>".  Read the server's
                  // response message.  If the message is "ok", get the file.
               String message = incoming.getln();
               if (! message.equals("ok")) {
                  System.out.println("File not found on server.");
               PrintWriter fileOut;  // For writing the received data to a file.
               if (args.length == 2) {
                     // Use the third parameter as a file name.
                   fileOut = new PrintWriter( new FileWriter(args[1]) );
               else {
                     // Use the second parameter as a file name,
                     // but don't replace an existing file.
                   File file = new File(args[0]);
                   if (file.exists()) {
                      System.out.println("A file with that name already exists.");
                      System.out.println("To replace it, use the three-argument");
                      System.out.println("version of the command.");
                   fileOut = new PrintWriter( new FileWriter(args[1]) );
               while (incoming.peek() != '\0') {
                      // Copy lines from incoming to the file until
                      // the end of the incoming stream is encountered.
                   String line = incoming.getln();
               if (fileOut.checkError()) {
                  System.out.println("Some error occurred while writing the file.");
                  System.out.println("Output file might be empty or incomplete.");
         catch (Exception e) {
            System.out.println("Sorry, an error occurred while reading data from the server.");
            System.out.println("Error: " + e);
      //new ConnectionHandler(folder,connection);      
      } // end main()

      //start connectionhandler here

   }//end server2 class

But im getting the following error, when i try to compile the file:

E:\server2.java:86: unreachable statement
         try {
1 error

Can anyone see where the code is going wrong? or what am i missing?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You need to make sure you have your return statements following a logical code progression. If your code must exit before a certain according to your return statements, it will report the above error.

The code enters a while(true) loop to sit and wait for connections.  The only way out of this is if an exception occurs.  In the catch, you return (exiting the main method), so nothing after that catch can ever be executed.

You probably can't do what you're trying to do without making some more serious changes.  eg. the server part needs to run in it's own thread.

Why are you "mashing" ;-) them together anyway?  The whole point of client/server is that you separate the two parts.
fimbriaAuthor Commented:
So if i remove the "return" statement wil the code continue?
...or does the code further work than just removing and replacing the "return" command?

what do u mean by the "server" doing its own thread, would this be part of the "main"?

Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

>>  So if i remove the "return" statement wil the code continue?

No.  This is why I said that you need to make more serious changes.

I assume that previously this while loop (for the server to accept connections) was running in a separate VM (possibly, but not necessarily on another machine).  The while loop sits and waits forever for connections to be made from the client.  When a connection is made, at the moment it does nothing but start the loop again and wait for another connection.  The code after this (the client part) will never execute.

>> what do u mean by the "server" doing its own thread

I mean that you need another class that can run as a separate thread (ie. extends Thread or implements Runnable).  The while loop that waits for connections should go in there so that you can start this thread and get on with the client code.

Unless you have a really good reason for trying to get all this into a single application, I would strongly recommend keeping the server code and client code separate.

Regardless of whether you keep the code in one lump like this or split it out again, you'll need to add some code after the accept() line, otherwise nothing will happen when clients try to connect.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
fimbriaAuthor Commented:
what sort of thing do you suggest after the "accept ()" line?

I would rather do the model as a separate server and client, just its for a uni project...so...my hands are tied.
>> what sort of thing do you suggest after the "accept ()" line?

What should the server do?  Maybe read data from the client?  Create data and send it to the client?

What instructions have you been given for the project (in particular, what is the system supposed to do and what restrictions have been placed on you that prevents you from creating separate code for the server and client)?
fimbriaAuthor Commented:
see specification below:

1.The most basic functionality is to provide a mechansim for transferring files between processes. If you think about it a file transfer is just a basic file copy program split into 2 halves - one side reads from a file and writes to a socket and the other side reads from a socket and writes to a file. You don't have to provide the functionality or mechanism of FTP!
Therefore you could start by writing a simple client that requests a file by name and a simple server that sends that file.

2.You want either side of the communication to be able to request the file or to have it requested. Therefore your next step is to put the server and the client together in one. You will then have a peer-to-peer transfer.
This is going to be a bit trickier because your server will have to be able to respond to either an incoming request on the server socket OR to a keyboard input specifying the file to fetch so that you can start a "client" to request it

3.The final stage is to modify the "client" part to implement a discovery to find out which server has the file before it can request it.

At the moment i have done number 1... trying number 2 now
If you've done 1. and you're happy that it is working OK, then you should already have the code that follows the accept().

Even within one application, you're going to need to separate out the server and client portions of the code.  It would probably be worthwhile having a word with your tutor.  At least that way you'll get guidance on what he expects rather than what we would suggest (there should be more marks in it that way ;-))
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.