Exception handling in threads

Hi all,
I'm trying to figure out an efficient way for my main process that creates a few threads to know if an exception occurred in any of them. The best solution I think of is using Callable to return any exceptions that occurred. I don't need the main process to know what the exception was exactly (logging will happen in the thread), just that the thread ended prematurely. Is there another way to test for this?
Any suggestions would be appreciated!
Leon

how would this idea work in your case?
public interface ExceptionCallback {
  public void exception(Worker w);
public class Main implements ExceptionCallback {
  public static main(String[] args) {
    (new Main()).init();
  private void init() {
    (new Worker(this)).start();
  public void exception(Worker w) {
    Thread.State ts = w.getState();
     ... // deal with any problems
public class Worker extends Thread {
  ExceptionCallback main;
  Worker(ExceptionCallback ec) {
    main = ec;
  public void run() {
    try {
    } finally {
          main.exception(this);
}detecting if a thread exits abnormally sounds difficult. the only thing i have learned is that a thread can never die without invoking the "finally" block.
and, maybe it is best to have the thread inform the main method when it exits, rather than have the main method try and monitor each thread? that's what i tried to do in my code.

Similar Messages

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

  • Exception handling in  in insert statemnt

    i am inserting values in to a table in a procedure.for insert statemnt what are the possible exceptions that may occur.
    how to handle exceptions for that insert statement(other than when others)

    user639995 wrote:
    is there any possiblity to use if sql%rowcount = 0 then
    RAISE e1;
    like thisNot for an insert statement, no.
    sql%rowcount returns the number of rows effected by a DML statement.
    For any of the statements you can only check sql%rowcount after the DML statement successfully executes, and it will only return a 0 if no rows were effected by that DML statement e.g. if an update effected no rows or an insert ... select ... actually inserted no rows etc.
    If an exception occurs during a DML statement then execution will pass directly to the exception handler so you won't have the opportunity to test for sql%rowcount after the statement.
    You should have an exception handler for expected exceptions.
    If an exception is not expected then you should let your code raise it up so it is seen and not handled.
    example of defining exceptions for non-named error numbers...
    SQL> create table x (x number);
    Table created.
    SQL> insert into x values ('x');
    insert into x values ('x')
    ERROR at line 1:
    ORA-01722: invalid number
    SQL> set serverout on
    SQL> declare
      2    ex_not_number exception;
      3    pragma exception_init(ex_not_number, -1722);
      4  begin
      5    insert into x values (1);
      6    commit;
      7    insert into x values ('A');
      8    commit;
      9  exception
    10    when ex_not_number then
    11      dbms_output.put_line('An attempt to insert a value that is not a number was made.');
    12  end;
    13  /
    An attempt to insert a value that is not a number was made.
    PL/SQL procedure successfully completed.
    SQL> select * from x;
             X
             1
    SQL>Further details on exception handling here:
    [PL/SQL 101 : Exception Handling|http://forums.oracle.com/forums/thread.jspa?threadID=697262&tstart=50]

  • Exception handling in ODI - common exception handling framework

    Hi,
    I need to come up with a common exception handling framework in an environment where ESB and ODI are being used for interfacing and ELT operations. I am of the opinion that
    1. I am not able to find any documentation wrt exception handling when ODI is used? Can some one help me with some pointers?
    2, When I come up with a common exception handling framework using BPEL, will I be able to invoke the same from ODI.
    Thanks,
    Mahesh

    Thanks for the reply Allan. I haven't used BusinessWorks.
    I did go through this thread before and here's my understanding.
    1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
    2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
    Thanks,
    Mahesh

  • 11g ADF TaskFlow Exception Handling in BPM

    Hi Guys
    BPM 11g
    I have a human task that is implemented as an ADF task flow. I would like to be able to throw an exception from the ADF application and have it handled by the BPM process, does anyone know if this is possible or how I would do that?
    At the moment I have an ADF error page - I could return an "error" outcome to the process from that but an error is an error and it feels right to show that in the process instead of a normal outcome.
    anyone else worked through this?
    cheers,
    Steve

    help yourself with this thread - Re: Exception Handling
    it should answer your question

  • Exception Handling in Stripes framework

    Pls help me to setup the Exception handling...
    1.how to catch the exception occuring in ActionBean method,using our custom
    exception handle method?
    not sure to integrate this both?
    http://stripesframework.org/display/stripes/Exception+Handling
    becas in the example it shows only the MyExceptionHandler class ...how it is
    linked to the method in the ActionBean
    Thanks
    Kris

    The same answer as in: http://forum.java.sun.com/thread.jspa?threadID=5264689

  • Exception Handling related problem

    Can anybody tell me why it is not giving ArithmeticException.
    package pckg1;
    * @author anil_saini
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.io.FileNotFoundException;
    public class Average7 {
         public static void main(String[] args) throws InterruptedException,FileNotFoundException {
         try {                                                      // (1)            System.out.println(printAverage(100, 0));                                  // (2)
         } catch (ArithmeticException ae) {                         // (3)
         Thread.sleep(1000);
              ae.printStackTrace(); // (4)
    System.out.println("Exception handled in " + // (5)
         "main().");
         finally {
         System.out.println("Finally in main()."); // (6)
         System.out.println("Exit main()."); // (7)
    public static int printAverage(int totalSum, int totalNumber) {
         int average=0;
         try {                                                      // (8)
    average = computeAverage(totalSum, totalNumber); // (9)
         System.out.println("Average = " + // (10)
         totalSum + " / " + totalNumber + " = " + average);
         return average;
         } catch (IllegalArgumentException iae) {                   // (11)
              iae.printStackTrace(); // (12)
    System.out.println("Exception handled in " + // (13)
         "printAverage().");
         } finally {
    System.out.println("Finally in printAverage()."); // (14)
         return average;
         }     // (15)
    public static int computeAverage(int sum, int number) {
         System.out.println("Computing average.");
         if (number == 0) // (16)
    throw new ArithmeticException("Integer division by 0");// (17)
         return sum/number; // (18)
    Output
    =======================
    Computing average.
    Finally in printAverage().
    0
    Finally in main().
    Exit main().

    Because return statements in finally blocks are evil!
    int average = 0;
    try
    { // (8)
         average = computeAverage(totalSum, totalNumber); // (9)
         System.out.println("Average = " + // (10)
                   totalSum + " / " + totalNumber + " = " + average);
         return average;
    catch (IllegalArgumentException iae)
    { // (11)
         iae.printStackTrace(); // (12)
         System.out.println("Exception handled in " + // (13)
                   "printAverage().");
         throw new IllegalArgumentException();
    finally
         System.out.println("Finally in printAverage()."); // (14)
         return average; // (15)
    }You get an exception at (9), but finally is guaranteed to be executed, so the JVM executes it. Now you return in your finally block (15), and the JVM is left with the choice of executing your return statement or propagating the exception. Since, as said, finally is guaranteed to be executed, it returns and swallows the exception.
    That's why IMHO return statements in finally blocks should not be allowed.
    (Some compilers issue warnings)
    If you move your return statement out of the finally block, it will work as you'd expect it.

  • General Exception Handling

    Hello. In my applications I usually have a try catch(Throwable) block surrounding all the top code (the code in main()) to log and report errors and exceptions that is not caught anywhere else, and to have my application exit in a controlled way. But I recently noticed that exceptions thrown in event handling (i.e. java.awt.EventDispatchThread.run) are not caught by the try catch block in main().
    Are there any easy way to catch everything so my app can exit in a controlled way?
    If this is not possible which exceptions are not propagated to main()? I would guess that it's exceptions thrown in other threads, is this correct? If so, do I have to surround all event handling by try catch(Throwable) to be safe?
    I would like more information and guidelines about exception handling. Any book recommendations?
    Help appreciated, thanks!

    You should never let exceptions propagate outside your event handling methods.
    If you don't follow that rule, the java.awt.EventDispatchThread.run() method terminates and the Java Virtual Machine tries to print the stack trace to the terminal window (if there is one) and then exits, but not through your main() method.
    So, try /catch all Exceptions inside your event handler methods:
    // inside event handler method
    try {
        // handle event here
       } catch (Throwable t) {
         // handle errors and recover from errors here
         // and either log error or if important display message to the user.
       }There is no easy-lazy way to do exception handling by only having the try/catch block in main in this case.
    Note : If any of the listeners throws an exception none of the following listeners is called. Since there is no guarantee of the order in which listeners are called you cannot be sure which ones are called first.

  • Can i catch an exception from another thread?

    hi,guys,i have some code like this:
    public static void main(String[] args) {
    TimeoutThread time = new TimeoutThread(100,new TimeOutException("超时"));
    try{
    t.start();
    }catch(Exception e){
    System.out.println("eeeeeeeeeee");
    TimeoutThread will throws an exception when it runs ,but now i can't get "eeeeeeeeeee" from my console when i runs the main bolck code.
    i asked this question in concurrent forums,somebody told me that i can't.so ,i think if i can do this from aspect of jvm.
    thank you for your help
    Edited by: Darryl Burke -- Double post of how to catching exceptions from another thread locking

    user5449747 wrote:
    so ,i think if i can do this from aspect of jvm. What does that mean? You think you'll get a different answer in a different forum?
    You can't catch exceptions from another thread. It's that easy. You could somehow ensure that exceptions from that other thread are always caught and somehow passed to your thread, but that would be a different thing (you would still be catching the exception on the thread it is originating from, as is the only way).
    For example you can use setUncaughtExceptionHandler() on your thread to provide an object that handles an uncaught exceptions (and you could pass that uncaught exception to your other thread in some way).

  • Global Exception Handler

    Hello,
    I've implemented the Global Exception Handler how is saying at http://www.adobe.com/devnet/flex/articles/global-exception-handling.html
    Some errors are being catched by it, and others not.
    I looked at another thread here, but for him, the Debug Dialog was not appearing because another place was catching the exception for him.
    There are some way to catch all errors in just on place?
    I need this, because sometimes in production happen errors that we didn't find in development, but stills there.
    The SDK is 4.1 and minimum Flash Player for the applications is 10.1.
    Regards,
    Fredy.

    How to reproduce the error not being catched.
    Main Application:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                                     xmlns:s="library://ns.adobe.com/flex/spark"
                                     xmlns:mx="library://ns.adobe.com/flex/mx"
                                     minWidth="955"
                                     minHeight="600"
                                     xmlns:views="views.*"
                      applicationComplete="onApplicationComplete()">
              <s:layout>
                        <s:VerticalLayout />
              </s:layout>
              <fx:Script>
                        <![CDATA[
                                  import com.adobe.ac.logging.GlobalExceptionHandler;
                                  import com.adobe.ac.logging.LogHandlerAction;
                                  private var globalExceptionHandler:GlobalExceptionHandler;
                                  private function onApplicationComplete():void {
                                            globalExceptionHandler = new GlobalExceptionHandler();
                                            globalExceptionHandler.preventDefault = true;
                                            var lha:LogHandlerAction = new LogHandlerAction();
                                            globalExceptionHandler.handlerActions = [];
                                            globalExceptionHandler.handlerActions.push(lha);
                        ]]>
              </fx:Script>
              <mx:ViewStack id="vs" creationPolicy="none">
                        <views:FirstView  />
                        <views:SecondView />
              </mx:ViewStack>
              <s:Button label="Call Second View" click="vs.createDeferredContent()"/>
    </s:Application>
    First View:
    <?xml version="1.0" encoding="utf-8"?>
    <s:NavigatorContent xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
                         creationComplete="onCreationComplete()">
              <fx:Script>
                        <![CDATA[
                                  import mx.rpc.remoting.RemoteObject;
                                  private function onCreationComplete():void {
                                            trace("First Created!");
                        ]]>
              </fx:Script>
    </s:NavigatorContent>
    Second View:
    <?xml version="1.0" encoding="utf-8"?>
    <s:NavigatorContent xmlns:fx="http://ns.adobe.com/mxml/2009"
                                                      xmlns:s="library://ns.adobe.com/flex/spark"
                                                      xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300"
                                                      creationComplete="onCreationComplete()">
              <fx:Script>
                        <![CDATA[
                                  import mx.rpc.remoting.RemoteObject;
                                  private function onCreationComplete():void {
                                            trace("Second View created!");
                                            var ro:RemoteObject;
                                            ro.destination = "";
                        ]]>
              </fx:Script>
    </s:NavigatorContent>
    Regards,
    Fredy.

  • JSF Exception Handling Example

    Here is an example of catching a backend exception and displaying it on the UI. It seems like most of the examples in books and such concern themselves with Validators and Converters. If you are trying to catch a backend exception, and you just want to display a UI message for it, see if this will work for you:
    JSF tags:
    <h:commandLink id="myActionLink" value="#{msgs.myLinkText}" binding="#{MyFormBean.uiComponentLink}" action="#{MyFormBean.linkProcessingMethod}"></h:commandLink>
    <h:messages layout="table" errorClass="Errors" styleClass="AlignLeft"/>
    ...And now the exception handling and message creation inside of the managed bean:
    private HtmlCommandLink uiComponentLink;
    * Method that processes the link action
    * @return String (action ID)
    public String linkProcessingMethod()
         try
              // BEGIN: TEST ONLY
              if(1 == 1)     // Always true
                   throw new Exception("TEST ERROR MESSAGE DISPLAY");
              // END: TEST ONLY
         return "dummyPageReference";     // No reference for this in faces-config.xml. Redisplays same page.
         catch (Exception e)
             addFacesMessageForUI("Exception detected. Message: " +e.getMessage());
             return "dummyPageReference";
    * Add faces message for display on the UI
    * @param String uiMessage
    private void addFacesMessageForUI(String uiMessage)
         FacesMessage facesMessage = new FacesMessage(uiMessage);
         FacesContext facesContext = FacesContext.getCurrentInstance();
         // Passing null for the client ID argument to the FacesContext
         // addMessage() method specifies the message as not belonging
         // to any particular UI component. This will cause the message
         // to be displayed as a general message on the UI
         facesContext.addMessage(null,facesMessage);
    }

    chrisjohn wrote:
    Following link would be helpful
    [http://technologicalbrainstorm.wordpress.com/2009/09/19/exception-handling-in-jsf/]
    Thanks!!Please, don't resurrect old threads, and especially not to post link-spam. Your account will get blocked if you continue with it. I'm locking this thread.
    Kaj

  • Common Exception Handling

    I am trying to create a single BPEL process which is called from all my processes to handle a fault condition. To do this I need to pass in the complete error from the console.
    So for example I get the following error if I add no exception handling to my web service call (i.e. the process goes RED) :
    <bindingFault>
    <part name="code" >
    <code>GenericError</code>
    </part>
    <part name="summary" >
    <summary>Failed get wsdl service definition. Failed to get a WSDL service that support the portType "{http://ManualErrorHandler.integration}ManualExceptionHandler" in WSDL definition "{http://ManualErrorHandler.integration}
    ManualExceptionHandler". Please verify that WSDL portType "{http://ManualErrorHandler.integration}
    ManualExceptionHandler" is supported by a service in WSDL file. </summary>
    </part>
    </bindingFault>
    I would like to pass this complete text as a string input into my common process.
    Can this be done? I do not seem to be able to copying this data in an Assign...
    Pete

    Thanks for the reply Allan. I haven't used BusinessWorks.
    I did go through this thread before and here's my understanding.
    1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
    2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
    Thanks,
    Mahesh

  • RE: exception handling

    Wayne,
    When an exception occurs, Forte aborts the inner
    most compound statement, after executing the code
    of an exception handler if there is one. If the excep-
    tion is not handled, it still exists after the compound
    statement was aborted, so Forte now aborts the
    remaining inner most compound statement. This
    continues until Forte reaches the root compound
    statement of the tread (or "task" if you will). This
    one will also be aborted and that is the end of the
    thread (task). If you look at the debugger, you will
    see "RIP" in front of this thread. Sure, this thread
    was spawned by another thread. It was started
    by a "start task" call from within some compound
    statement in the parent thread, but this compound
    statement was probably long since closed. Forte
    can't pass the exception on to a higher level com-
    pound statement, because there is none. If the
    thread started with a method that had a return event
    and an exception event, and you started the task
    with "Completion = event" then Forte will post one
    of these events after the root compound statement
    was finished (in other words, the thread was stopped).
    From this event you can see, if the thread wasfinished succesfully or not.
    Of course, an event is not the same kind of thing
    as an exception. You can't raise events, or post
    exceptions.
    So, when an exception is not handled, only the thread
    where this exception occured is cancelled (including
    all it's child threads). The rest of the treads stay alive.
    -----Original Message-----
    From: Wayne Walker [SMTP:[email protected]]
    Sent: Wednesday 22 July 1998 13:49
    To: '[email protected]'
    Subject: exception handling
    I have a problem in handling exceptions detected in a task. I start a
    task
    which performs some function. I also have an event handler which
    recognizes the method_exception returned should an exception be
    detected.
    Once detected by the event handler I force the exception up to
    another
    process which displays the exception to the user. However, it appears
    that
    forte is intercepting the exception before my event handler can detect
    it
    and posts an exception message. Can anyone explain how this mechanism
    works and the best approach for handling exceptions myself vice Forte?
    Thanks,
    Wayne
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive
    <URL:http://pinehurst.sageit.com/listarchive/>-
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    My understanding is that if your client doesn't care (or cannot handle) the exception,
    you throw your exception WRARPPED with EJBException. This way, the container can
    roll back the transaction properly.
    If your client cares (or have the ability to recover) the exception, you should
    define your own exception. They should not be derived from RuntimeException or
    RemoteException or EJBException. If you want to make sure that the transactions
    are rolled back, you call setRollbackOnly() before you throw the exception.
    Charles
    soraya abbasi <[email protected]> wrote:
    I have tried to make my custom exception subclass RemoteException but
    that doesn't work.
    Does that mean to say you can't have custom exceptions thrown to a client?

  • Exception handling - Common exception handling framework

    Hi,
    I need to come up with a common exception handling framework in an environment where ESB and ODI are being used for interfacing and ELT operations. I am of the opinion that
    1. A generic exception handling framework can be built using BPEL and can be invoked from ESB. Is my understanding correct?
    2. Are there any ways that we can build this framework using ESB itself? I opinion that it's not possible as there is no concept of try-catch?
    3. I am not able to find any documentation wrt exception handling when ODI is used? Can some one help me with some pointers?
    4, When I come up with a common exception handling framework, will I be able to invoke the same from ODI.
    Thanks,
    Mahesh

    Thanks for the reply Allan. I haven't used BusinessWorks.
    I did go through this thread before and here's my understanding.
    1. ESB provides the ability of error handling (client management API) but not the exception handling i.e. I can't redirect the flow in case there is an exception in my primary flow. Am I right with my understanding?
    2. Error handling ability of ESB is limited to retryable exceptions viz-a-viz asynchrounous ESB processes (e.g. database listener not up) where in the process can be retried. Am I right here?
    Thanks,
    Mahesh

  • EDT custom exception handler

    Hi,
    Is there any posibility to add custom exception handler to EDT? I'm thinking to implement an automatic feed-back from a client aplication. When an exception occurs in EDT it will automatically send to server. The problem is that unsigned webstart application have no permissions to call Thread.setUncaughtExceptionHandler() on EDT.
    Is there any workaround?
    Anton

    Hi,
    Is there any posibility to add custom exception handler to EDT? I'm thinking to implement an automatic feed-back from a client aplication. When an exception occurs in EDT it will automatically send to server. The problem is that unsigned webstart application have no permissions to call Thread.setUncaughtExceptionHandler() on EDT.
    Is there any workaround?
    Anton

Maybe you are looking for

  • NMP 12 core D700s failing to initialize thunderbolt bus 0 if the hdmi cable is plugged in

    Hey Everyone, I have a new Mac Pro, 12 core model with D700s, 32 GB RAM.  I started having issues about a month ago after only owning it for one month.  I noticed that sometimes when I booted up, some of my thunderbolt buses were not initializing.  I

  • Console fails on solaris 8

    Hello, I installed DS50 on a solaris 8 machine. When I start the console I get the following messages: Font specified in font.properties not found [-b&h-lucida sans-medium-r-normal-sans-*-%d-*-*-p-*-iso8859-1] Font specified in font.properties not fo

  • Starting new task in FM

    Hi, I have FM 'update_table' with asynchrounous call(FM which use starting new task). This FM updates the table and commits the work.But when I try to read the datas from table I don't get the updated datas.This happens only in in real scenario. When

  • Plz help load class files

    hai forum, Plz help me out regarding this trouble. I have extracted class files of a jar file into a local directory D:\myClass. Now i need to access these class files.I loaded the path D:\myClass using URL ClassLoader.                              

  • How to use daemon

    Hi all, I have to automatically schedule DTP right after loading to PSA.Can anybody suggest me how to use this daemon ? Regards    KK