Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Aug 6th, 2006, 7:46 PM   #1
Harakim
Hobbyist Programmer
 
Join Date: May 2006
Location: West Jordan, Utah, United States
Posts: 176
Rep Power: 3 Harakim is on a distinguished road
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.
Harakim is offline   Reply With Quote
Old Aug 7th, 2006, 5:03 AM   #2
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
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.
grumpy is offline   Reply With Quote
Old Aug 7th, 2006, 9:11 AM   #3
ReggaetonKing
Sexy Programmer
 
ReggaetonKing's Avatar
 
Join Date: Nov 2005
Location: New Jersey
Posts: 891
Rep Power: 3 ReggaetonKing is on a distinguished road
Send a message via AIM to ReggaetonKing
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!
__________________
I would love to change the world, but they won't give me the source code!
ReggaetonKing is offline   Reply With Quote
Old Aug 7th, 2006, 9:14 AM   #4
ReggaetonKing
Sexy Programmer
 
ReggaetonKing's Avatar
 
Join Date: Nov 2005
Location: New Jersey
Posts: 891
Rep Power: 3 ReggaetonKing is on a distinguished road
Send a message via AIM to ReggaetonKing
P.S. - This should be moved to the Java Section.
__________________
I would love to change the world, but they won't give me the source code!
ReggaetonKing is offline   Reply With Quote
Old Aug 7th, 2006, 9:27 AM   #5
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
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.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote
Old Aug 7th, 2006, 10:15 AM   #6
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 3 MBirchmeier is on a distinguished road
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
MBirchmeier is offline   Reply With Quote
Old Aug 7th, 2006, 10:18 AM   #7
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
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.
grumpy is offline   Reply With Quote
Old Aug 7th, 2006, 12:04 PM   #8
ReggaetonKing
Sexy Programmer
 
ReggaetonKing's Avatar
 
Join Date: Nov 2005
Location: New Jersey
Posts: 891
Rep Power: 3 ReggaetonKing is on a distinguished road
Send a message via AIM to ReggaetonKing
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.
__________________
I would love to change the world, but they won't give me the source code!
ReggaetonKing is offline   Reply With Quote
Old Aug 7th, 2006, 3:01 PM   #9
Harakim
Hobbyist Programmer
 
Join Date: May 2006
Location: West Jordan, Utah, United States
Posts: 176
Rep Power: 3 Harakim is on a distinguished road
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.
Harakim is offline   Reply With Quote
Old Aug 7th, 2006, 3:17 PM   #10
Jimbo
Battle Programmer
 
Jimbo's Avatar
 
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 763
Rep Power: 3 Jimbo is on a distinguished road
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...
Jimbo is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Could some please explain classes to me... TCStyle C++ 10 Feb 20th, 2006 3:51 PM
AhhH!!! I can't find anything on this exception... stakeknife ASP 2 Sep 26th, 2005 7:48 AM
Ranting uman C++ 27 Jun 17th, 2005 12:02 PM
exception handling chrome_knob Java 2 May 19th, 2005 5:45 PM
Handling exceptions when using threads bobc C# 0 Feb 8th, 2005 10:56 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 11:31 AM.

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