Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Software Design and Algorithms (http://www.programmingforums.org/forum64.html)
-   -   Exception Handling with Threads (http://www.programmingforums.org/showthread.php?t=10967)

Harakim Aug 6th, 2006 8:46 PM

Exception Handling with Threads
 
I am writing a client application in Java. It can open connections to a few different servers at once. Each connection has it's own Thread. I thought to myself, how should I handle exceptions? I would like to hear other's thoughts before I share what I am currently doing.

Thanks.

grumpy Aug 7th, 2006 6:03 AM

There is no single correct answer to your question. The way you handle exceptions depends on what exceptions are thrown, the reasons they are thrown, what needs to be done to recover when they are, how the threads that may encounter errors interact with each other, etc etc.

ReggaetonKing Aug 7th, 2006 10:11 AM

The server code
:

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

public class ThreadedServer
{
        public static void main(String[] args )
        {
                try
                {
                        int i = 1;
                        ServerSocket s = new ServerSocket(6989); //make up a port number I did
                        while(true)
                        {
                                Socket incoming = s.accept();
                                System.out.println("Spawning " + i);
                                ThreadedEchoHandler ter = new ThreadedEchoHandler(incoming, i);
                                Thread t = new Thread(ter);
                                t.start();
                                i++;
                        }
                }
                catch(Exception e)
                {
                        e.printStackTrace();
                }
        }
}
class ThreadedHandler implements Runnable
{
        private Socket incoming;
        private int counter;
       
        public ThreadedEchoHandler(Socket i, int c)
        {
                incoming = i;
                counter = c;
        }
        public void run()
        {
                try
                {
                        try
                        {
                                InputStream instream = incoming.getInputStream();
                                OutputStream outstream = incoming.getOutputStream();
                                Scanner in = new Scanner(instream);
                                PrintWriter out = new PrintWriter(outstream);
                                out.println( "Welcome to CEL Server! Enter ADIOS to exit." );
                                boolean done = false;
                                while(!done && in.hasNextLine())
                                {
                                        String l = in.nextLine();
                                        System.out.println("Client" + counter + " says: " + l);
                                        if (l.trim().equals("BYE"))
                                                done = true;
                                }
                        }
                        finally
                        {
                                incoming.close();
                        }
                }
                catch(Exception e)
                {
                        e.printStackTrace();
                }
        }
}

The client code
:

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

public class EchoServer
{
        public static void main(String[] args)
        {
                try
                {
                        ServerSocket s = new ServerSocket(6989);
                        //establish server socket

                        Socket incoming = s.accept();
                        //waits for incoming client
                        try
                        {
                                InputStream instream = incoming.getInputStream();
                                OutputStream outstream = incoming.getOutputStream();
                               
                                Scanner in = new Scanner(instream);
                                PrintWriter out = new PrintWriter(outstream, true /* autoFlush */);
                               
                                out.println( "Welcome to my Server! Enter ADIOS to exit." );
                                boolean done = false;
                                while (!done && in.hasNextLine())
                                {
                                        String line = in.nextLine();
                                        if(line.trim().equals("ADIOS"))
                                        {
                                                out.println("Server Disconnected");
                                                break;
                                        }
                                        System.out.println(incoming.getRemoteSocketAddress() + " says:" + line);
                                }
                        }
                        finally
                        {
                                incoming.close();
                        }
                }
                catch(IOException e)
                {
                        e.printStackTrace();
                }
        }
}


Exception catching is a must when dealing with the io and net packages. Read up the Java Doc for JSE 1.5 and see what methods throw what exception. Once you get the hang of it, it's very very easy. I did this a long time ago, Networking in Java is really fun!

ReggaetonKing Aug 7th, 2006 10:14 AM

P.S. - This should be moved to the Java Section.

DaWei Aug 7th, 2006 10:27 AM

I disagree. It's a design issue that happens to be implemented in Java, but the issues are more widely applicable. A person seeking solutions in this area is more likely to look here than in a forum for a specific language. It's why this forum was recently added.

MBirchmeier Aug 7th, 2006 11:15 AM

Aervos and I recently had a discussion about this in the VB.NET forum. We got into it pretty heavily, and there's a few good links in the discussion.
Linky: http://www.programmingforums.org/for...ight=Exception

As a summary, some like to use more exceptions, others less, there's good reasons for each method. It's up to you to decide what's appropriate for your project.

-MBirchmeier

grumpy Aug 7th, 2006 11:18 AM

Indeed. Exceptions are one type of error handling mechanism. One way of handling exceptions is not to throw them at all: in other words, managing error conditions in another way. Error handling philosophies are basic design issues for any program.

For some discussion of exceptions, with examples in C++, but the same basic design issues, look at a discussion by Herb Sutter or this discussion by David Abrams or this discussion by David Abrams on exception safety or a powerpoint presentation by Andree Alexandrescu on use of exceptions versus return codes

Little specifically to do with threads, but if you can't get it working with one thread you haven't a hope with multithreading.

ReggaetonKing Aug 7th, 2006 1:04 PM

Though some method throw exception. It's a must in some cases that exceptions have to be caught. Take the example I wrote for you in mind, that exceptions handling was a must. In Java, some method and constructor throw exception.

With that said, if you don't have to use exceptions, don't use them. There are many other alternatives to exceptions where they are not required.

Exception handling in Java slows down performance of a program. Where you use a "throw/catch" statement, try to use an "if" statement instead.

Harakim Aug 7th, 2006 4:01 PM

Thanks for all of the input. I didn't realize I could catch errors from a running Thread the same way that you normally would.

The method I chose is more in line with your last post, reggaeton_king. Any Exception that happens in the Threaded connection to the server will be fatal. The Server sends an exit message when it wants a client to exit. I simply created an exit message and threw it into the client's message queue so it looks like it came from the server. The client decodes it normally and hands it just as if the server had sent it, although it can tell:
A) that it came from the client.
B) which exception caused it.

I am glad you posted that code, because I am positive that will help me in the near future. :)

Jimbo Aug 7th, 2006 4:17 PM

Quote:

Originally Posted by reggaeton_king
With that said, if you don't have to use exceptions, don't use them. There are many other alternatives to exceptions where they are not required.

Exception handling in Java slows down performance of a program. Where you use a "throw/catch" statement, try to use an "if" statement instead.

I prefer using exceptions to returning error codes. For an error code to be handled correctly, the handler must know what the code means, which increases coupling between the calling code and the error returning code. Furthermore, error codes can only be handled within 1 stack frame (or returned through the stack by hand), whereas exceptions are more flexible. It really depends on the situation, but I tend to use exceptions. I'd rather the program was simpler to write/manage than whether it got slowed down ever so slighly by using exceptions...


All times are GMT -5. The time now is 12:21 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC