How to pass the caught exception in Thread.run back to the main program?

I have following three Java files (simplified from a real world application I am developing, see files at the end of this posting):
1. ThreadTest.java: The main program that invokes the Manager.run()
2. Manager.java: The manager that creates a thread to execute the Agent.run() for each agent
3. Agnet.java: The run() method can throw Exception
My goal is twofold:
1. To execute the run() method of an Agent in a thread (the reason for this is there are many Agents all managed by a Manager)
2. To catch the exception thrown by Agent.run() in the main program, ThreadTest.main() -- so the main program can alert the exceptions
My problem:
Bottomline: I cannot pass the exception thrown by Agent.run() in the Thread.run() back to the main program.
Explanation:
The signature of Thread.run() (or Runnable.run()) is
public void run();
Since it does not have a throws clause, so I have to try/catch the Agent.run(), and rethrow a RuntimeException or Error. However, this RuntimeException or Error will not be caught by the main program.
One work-around:
Subclass the ThreadGroup, override the ThreaGroup.uncaughtException() methods, and spawn the threads of this group. However, I have to duplicate the logging and exception alerts in the uncaughtException() in addition to those already in the main program. This makes the design a bit ugly.
Any suggestions? Am I doing this right?
Thanks,
Xiao-Li "Lee" Yang
Three Java Files:
// Agent.java
public class Agent {
public void run() throws Exception {
throw new Exception("Test Exception"); // Agent can throw execptions
// Manager.java
public class Manager {
public void run() throws Exception {
try {         // <===  This try/catch is virtually useless: it does not catch the RuntimeException
int numberOfAgents = 1;
for (int i = 0; i < numberOfAgents; i++) {
Thread t = new
Thread("" + i) {
public void run() {
try {
new Agent().run();
} catch (Exception e) {
throw new RuntimeException(e); // <=== has to be RuntimeException or Error
t.start();
} catch (Exception e) {
throw new Exception(e); // <== never got here
// ThreadTest.java
public class ThreadTest {
public static void main(String[] args) {   
try {
Manager manager = new Manager();
manager.run();
} catch (Throwable t) {
System.out.println("Caught!"); // <== never got here
t.printStackTrace();

The problem is, where could you catch it anyway?
try {
thread.start();
catch(SomeException e) {
A thread runs in a separate, er, thread, that the catch(SomeException) isn't running within. Get it?
Actually the Thread class (or maybe ThreadGroup or whatever) is the one responsible for invoking the thread's run() method, within a new thread. It is the one that would have to catch and deal with the exception - but how would it? You can't tell it what to do with it, it (Thread/ThreadGroup) is not your code.

Similar Messages

  • How to throw Exception in Thread.run() method

    I want to throw exception in Thread.run() method. How can I do that ?
    If I try to compile the Code given below, it does not allow me to compile :
    public class ThreadTest {
         public static void main(String[] args) {
         ThreadTest.DyingThread t = new DyingThread();
         t.start();
         static class DyingThread extends Thread {
         public void run() {
         try {
                   //some code that may throw some exception here
              } catch (Exception e) {
              throw e;//Want to throw(pass) exception to caller
    }

    (a) in JDK 1.4+, wrap your exception in RuntimeException:
    catch (Exception e)
    throw new RuntimeException(e);
    [this exception will be caught by ThreadGroup.uncaughtException() of this thread's parent thread group]
    In earlier JDKs, use your own wrapping unchecked exception class.
    (b) if you know what you are doing, you can make any Java method throw any exception using Thread.stop(Throwable) regardless of what it declares in its "throws" declaration.

  • I get the message Exception in thread "main" java.lang.StackOverflowError

    I'm trying to make a program for my class and when I run the program I get the error Exception in thread "main" java.lang.StackOverflowError, I have looked up what it means and I don't see where in my program would be giving the error, can someone please help me, here is the program
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    // This visual application allows users to "shop" for items,
    // maintaining a "shopping cart" of items purchased so far.
    public class ShoppingApp extends JFrame
    implements ActionListener {
    private JButton addButton, // Add item to cart
    removeButton; // Remove item from cart
    private JTextArea itemsArea, // Where list of items for sale displayed
    cartArea; // Where shopping cart displayed
    private JTextField itemField, // Where name of item entered
    messageField; // Status messages displayed
    private ShoppingCart cart; // Reference to support object representing
    // Shopping cart (that is, the business logic)
    String itemEntered;
    public ShoppingApp() {
    // This array of items is used to set up the cart
    String[] items = new String[5];
    items[0] = "Computer";
    items[1] = "Monitor";
    items[2] = "Printer";
    items[3] = "Scanner";
    items[4] = "Camera";
    // Construct the shopping cart support object
    cart = new ShoppingCart(items);
    // Contruct visual components
    addButton = new JButton("ADD");
    removeButton = new JButton("REMOVE");
    itemsArea = new JTextArea(6, 8);
    cartArea = new JTextArea(6, 20);
    itemField = new JTextField(12);
    messageField = new JTextField(20);
    // Listen for events on buttons
    addButton.addActionListener(this);
    removeButton.addActionListener(this);
    // The list of items is not editable, and is in light grey (to
    // make it distinct from the cart area -- this would be done
    // better by using the BorderFactory class).
    itemsArea.setEditable(false);
    itemsArea.setBackground(Color.lightGray);
    cartArea.setEditable(false);
    // Write the list of items into the itemsArea
    itemsArea.setText("Items for sale:");
    for (int i = 0; i < items.length; i++)
    itemsArea.append("\n" + items);
    // Write the initial state of the cart into the cartArea
    cartArea.setText("No items in cart");
    // Construct layouts and add components
    JPanel mainPanel = new JPanel(new BorderLayout());
    getContentPane().add(mainPanel);
    JPanel controlPanel = new JPanel(new GridLayout(1, 4));
    controlPanel.add(new JLabel("Item: ", JLabel.RIGHT));
    controlPanel.add(itemField);
    controlPanel.add(addButton);
    controlPanel.add(removeButton);
    mainPanel.add(controlPanel, "North");
    mainPanel.add(itemsArea, "West");
    mainPanel.add(cartArea, "Center");
    mainPanel.add(messageField, "South");
    public void actionPerformed(ActionEvent e)
    itemEntered=itemField.getText();
    if (addButton==e.getSource())
    cart.addComputer();
         messageField.setText("Computer added to the shopping cart");
    public static void main(String[] args) {
    ShoppingApp s = new ShoppingApp();
    s.setSize(360, 180);
    s.show();
    this is a seperate file called ShoppingCart
    public class ShoppingCart extends ShoppingApp
    private String[] items;
    private int[] quantity;
    public ShoppingCart (String[] inputitems)
    super();
    items=inputitems;
    quantity=new int[items.length];
    public void addComputer()
    int x;
    for (x=0; "computer".equals(itemEntered); x++)
         items[x]="computer";
    please somebody help me, this thing is due tomorrow I need help asap!

    First, whenever you post, there is a link for Formatting Help. This link takes you to here: http://forum.java.sun.com/features.jsp#Formatting and tells you how to use the code and /code tags so any code you post will be easily readable.
    Your problem is this: ShoppingApp has a ShoppingCart and ShoppingCart is a ShoppingApp - that is ShoppingCart extends ShoppintApp. You are saying that ShoppingCart is a ShoppingApp - which probably doesn't make sense. But the problem is a child class always calls one of its parent's constructors. So when you create a ShoppingApp, the ShoppingApp constructor tries to create a ShoppingCart. The ShoppingCart calls its superclass constructor, which tries to create a ShoppingCart, which calls its superclass constructor, which tries to create a ShoppingCart, which...
    It seems like ShoppingCart should not extend ShoppingApp.

  • Determine the type of the caught exception

    Hi!
    Here is my problem :
    I'm using a web service and the method I call throws different types of Exception (RemoteException, ServiceException, etc...)
    And, the reaction to the caught exception depends on its type, that's why I need to determine what type of exception i've caught. I know that with C# I use the boolean function is :
    if (exception is TypeOfException1)
        // associated reaction
    else if(exception is TypeOfException2)
       // associated reaction
    }Is there any method or any other way in Java to do that?
    Thanks a lot,
    Gan�che.

    >
    Here is my problem :
    I'm using a web service and the method I call throws different types of Exception (RemoteException, ServiceException, etc...)
    And, the reaction to the caught exception depends on its type, that's why I need to determine what type of exception i've caught. >
    try {
      // stuff that may cause exceptions..
    } catch(RemoteException re) {
      // deal with this re
    } catch(ServiceException se) {
      // deal with this se
    } catch (Throwable didNotExpectThis) {
      // exceptional!
      didNotExpectThis.printStackTrace();
    }

  • When mousing over text, the cursor flickers constantly (with each letter passed) from arrow to i-beam and back.  The problem occurs in both MS Word and Pages.  Any idea of how to resolve this annoying problem is appreciated.  System: 10.10.1

    When mousing over text, the cursor flickers constantly (with every letter passed) from arrow to i-beam and back.  The problem occurs in both MS Word 2011 and Pages.  Any idea of how to solve this annoying problem will be much appreciated.  System 10.10.1 on a MacPro (Late 2013)

    The mouse is controlled by the OS so don't guess any app other than a mouse driver or OS X itself would be able to cause this sort of flicker issue.
    Have you seen the following and is it what you are seeing? Maybe you could make a movie (Quicktime is great for this this to make a screen recording) - but not sure how to attach a movie to these discussions as mine is grayed out and can't be selected (to the right of the insert image). Here is the what I found for a search of "mouse cursor flickers os x yosemite"
         https://www.youtube.com/watch?v=ZNQ0D84DdF4
    What kind of mouse are you using? Is the mouse driver up to date if it's a third party mouse?

  • I downloaded a new version of firefox. It said it had problems with my norton toolbar and now it doesn't feature it in the window. I'm not that comp savvy. How do I either get the Norton toolbar up or go back to the old firefox? Thank you.

    I downloaded a new version of firefox. It said it had problems with my norton toolbar and now it doesn't feature it in the window. I'm not that comp savvy. How do I either get the Norton toolbar up or go back to the old firefox? Thank you.

    Please authorize ADE 3 with same credentials that you used with older version of ADE

  • I have all my music on an external media drive that has crashed. How can I get the music of my ipod touch back onto the comupter without loosing the music when it syncs?

    I have all my music on an external media drive that has crashed. How can I get the music of my ipod touch back onto the comupter without loosing the music when it syncs. in order to start rebuilding my music collection?

    You should be able to recover the media with the tips in  this post from forum regular Zevoneer but I'm not sure what the implications are for your application settings. You can probably transfer your purchases into a newly authorised library, backup the device, recover any other media using third party tools, then restore the device from the backup. That should switch the assocation of the device to the new library but it is not something I've personally tested.
    When you get it all working, make a backup!
    tt2

  • How do i change the artist view in itunes 11 back to the original view?

    How do i change the artist view in itunes 11 back to the original or pre itunes 11 view?

    You can't. iTunes 11 has different ways of viewing your library from earlier builds. You can restore some of the look/function of the old version by turning on the menu bar (ctrl-b), sidebar (ctrl-s) and also clicking the magnifying glass then unticking Search Entire Library to restore the old search behaviour.
    If that isn't enough the see this post on how to roll back to iTunes 10.7.
    tt2

  • My pc was stolen and now i want to transfer the music from the ipod touch to the new computer, but sync only allows the other way. How can i do that? I need to back up the music!

    my pc was stolen and now i want to transfer the music from the ipod touch to the new computer, but sync only allows the other way. How can i do that? I need to back up the music!

    If it is purchased music from itunes you can redownload it.
    Follow instructions at link below.
    http://support.apple.com/kb/HT2519

  • HT201269 I restored my iphone and now it has gone back to factory settings. How do I transfer all the purachsed items from my itunes back onto the phone?

    I restored my iphone and now it has gone back to factory settings. How do I transfer all the purachsed items from my itunes back onto the phone?

    Hello whytea4
    Check out the articles below and choose the one for your computer to sync media and apps to your iPhone.
    iTunes 11 for Mac: Set up syncing for iPod, iPhone, or iPad
    http://support.apple.com/kb/PH12113
    iTunes 11 for Windows: Set up syncing for iPod, iPhone, or iPad
    http://support.apple.com/kb/PH12313
    Thanks for using Apple Support Communities.
    Regards,
    -Norm G.

  • I'm trying to back up 10.6.8 (snow leopard) and all my files before upgrade to Mavericks.  I have an old but sturdy external hard drive...how many GB available will I probably need to back up the whole thing? thanks!

    I'm trying to back up 10.6.8 (snow leopard) and all my files before upgrade to Mavericks.  I have an old but sturdy external hard drive...how many GB available will I probably need to back up the whole thing? thanks!

    You will need a separate partition unless you plan to use the entire drive. You will need an amount of space somewhat larger than the total space now used on your startup drive. If you select the startup drive's Desktop icon, then press COMMAND-I to open the Get Info window. Used space will be shown in the topmost panel. Add a GB or two to that number to determine how much space you'll need for the backup.
    Do not backup on a drive that has any files you want to keep. You can make a bootable backup as follows:
    Clone using Restore Option of Disk Utility
      1. Open Disk Utility in the Utilities folder.
      2. Select the destination volume from the left side list.
      3. Click on the Restore tab in the DU main window.
      4. Select the destination volume from the left side list and drag
           it to the Destination entry field.
      5. Select the source volume from the left side list and drag it to
          the Source entry field.
      6. Double-check you got it right, then click on the Restore button.
    Destination means the external backup drive. Source means the internal startup drive.

  • How do you "Unsort" a column to get it back to the way it was when you opened it?

    How do you "Unsort" a column to get it back to the way it was when you opened it?
    I like to sort by price or alphabetical etc but then I want to return the cells to where they were and I can't figure out a way to do that.
    For instance, the rows that don't matter so much like the ones that just describe what date is the follow are now all together and I want it back the way it was when I opened the document without losing any changes I've met to other things in the doc since I sorted.
    Can anyone help with this?
    Thanks.
    Tim

    Hi fl2,
    Adding to replies from Wayne and Barry. After you open that Numbers document, insert another column into a table before you sort it. The column can be anywhere in that table. Here is Column A (labelled "Original") that I inserted. It has numbers in sequence (1, 2, 3...)
    As Barry said, these must be numbers, not the results of a formula.
    Now you can sort by any column to your heart's delight and always go back to the original order by sorting that table by column A.
    Regards,
    Ian.

  • I just got an iphone and am trying to connect it to my itunes account.  Getting the message " This iphone cannot be used because the Apple Mobile Device service is not started.  How do I start it?  Have already been back to the store with it and no change

    I just got an iphone and am trying to connect it to my itunes account.  Getting the message " This iphone cannot be used because the Apple Mobile Device service is not started.  How do I start it?  Have already been back to the store with it and no change.

    http://tinyurl.com/3hs3g2u

  • How do I turn off wifi syncing and go back to the cable sync in iTunes?

    How do I turn off wifi syncing and go back to the cable sync in iTunes?

    Select the device in iTunes and uncheck WiFi syncing on the Summary pane of it's sync settings.

  • Someone hacked my computer and set up a new administrative account by re-registering my computer. I can not access this account nor delete it. How can I fix this and get my computer back to the way it was?

    Someone hacked my computer and set up a new administrative account by re-registering my computer. I can not access this account nor delete it. How can I fix this and get my computer back to the way it was? And also prevent this from being able to happen again. I have the link the kid used (http://www.ihackintosh.com/2009/05/how-to-hack-the-user-password-in-mac-os-x-wit hout-an-os-x-cd/) Apparently he used hack 2. HELP PLEASE!

    Not sure why you can't delete that account. If you have admin privileges, you should be able to. Sounds like you only removed the Home Folder for that account.
    You should highlight/select the account you want to remove and then click the minus button. Might need to unlock the padlock with your admin password.
    Have a look at these articles from Apple, if necessary.
    http://docs.info.apple.com/article.html?path=Mac/10.5/en/8235.html
    http://docs.info.apple.com/article.html?path=Mac/10.5/en/8162.html
    http://support.apple.com/kb/DL1399

Maybe you are looking for