Thread throwing an Exception

I

IveCal

Hello, I got this code from David Reilly's site. What this prog does is
terminate the prog after a specified time. What I want to do is just
throw an Exception to be caught by other java programs. I tried to
throw an exception in timeout (ex. timeout() throws Exception) and run
(ex. run throws Exception) methods but it is not allowed. Please help.

import java.net.*;

public class Timer extends Thread
{
/** Rate at which timer is checked */
protected int m_rate = 100;

/** Length of timeout */
private int m_length;

/** Time elapsed */
private int m_elapsed;

/**
* Creates a timer of a specified length
* @param length Length of time before timeout occurs
*/
public Timer ( int length )
{
// Assign to member variable
m_length = length;

// Set time elapsed
m_elapsed = 0;
}


/** Resets the timer back to zero */
public synchronized void reset()
{
m_elapsed = 0;
}


/** Performs timer specific code */
public void run()
{
// Keep looping
for (;;)
{
// Put the timer to sleep
try
{
Thread.sleep(m_rate);
}
catch (InterruptedException ioe)
{
continue;
}

// Use 'synchronized' to prevent conflicts
synchronized ( this )
{
// Increment time remaining
m_elapsed += m_rate;

// Check to see if the time has been exceeded
if (m_elapsed > m_length)
{
// Trigger a timeout
timeout();
}
}

}
}

// Override this to provide custom functionality
public void timeout()
{
System.err.println ("Network timeout occurred.... terminating " );
System.exit(1);
}
}
 
M

Matt Humphrey

IveCal said:
Hello, I got this code from David Reilly's site. What this prog does is
terminate the prog after a specified time. What I want to do is just
throw an Exception to be caught by other java programs. I tried to
throw an exception in timeout (ex. timeout() throws Exception) and run
(ex. run throws Exception) methods but it is not allowed. Please help.

You cannot throw an exception into another program or even another thread.
You can, however, signal (or interrupt) the other thread when the exception
or other condition appears in the timer and that signal can be used to throw
an exception or make the other thread do something. You'll have to say more
about what you're really trying to do--exceptions are probably not the way
to accomplish it.

Matt Humphrey (e-mail address removed) http://www.iviz.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top