Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


unreachable statement try { error

Posted on 2003-12-10
Medium Priority
Last Modified: 2008-03-03

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?

Question by:fimbria
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
LVL 86

Expert Comment

ID: 9913096
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.

LVL 15

Expert Comment

ID: 9913160
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.

Author Comment

ID: 9914834
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"?

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 15

Accepted Solution

jimmack earned 1000 total points
ID: 9914943
>>  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.

Author Comment

ID: 9916723
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.
LVL 15

Expert Comment

ID: 9916767
>> 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)?

Author Comment

ID: 9916841
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
LVL 15

Expert Comment

ID: 9916982
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 ;-))
LVL 15

Expert Comment

ID: 10248067

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question