Results 1 to 3 of 3

Thread: Handling Exceptions raised from inside a thread

  1. #1

    Handling Exceptions raised from inside a thread

    Hey guys,

    At this moment, I'm looking at threads more closely and it seemed to me that before you deploy threads at a large scale in your application, you have to think about how to trap and handle exceptions.

    First, I'm not a fan of this:
    Code:
    procedure TSubsystemThread.Execute;
    begin
      try
        //do your stuff here
      except  //eat all exceptions
      end;
    end;
    IMHO, this is one of the most awfull things you can do to yourself (programming-wise that is ), as you make it really hard to find errors later on.

    So I was looking at a better solution and found this (2nd example on page):
    http://edn.embarcadero.com/article/10452

    What strikes me here, is that to make the mechanism work, you make a call to ExceptObject(), which seems to access global exception information. I might be nitpicking here, but is this thread-safe?

    Having said that, isn't the following solution alot better?
    Code:
    procedure TMyThread.Execute;
    begin
      FException := nil;
      try
        // raise an Exception
        raise Exception.Create('I raised an exception');
      except
        on E: Exception do 
          HandleException(E);  //Pass exception object to handler, and then to form
      end;
    end;
    
    procedure TMyThread.HandleException(ExceptionObject: Exception);
    begin
      FException := ExceptionObject;
      try
        // Don't show EAbort messages
        if not (FException is EAbort) then
          Synchronize(DoHandleException);
      finally
        FException := nil;
      end;
    end;
    Does anyone have experience with this? Seems like an obligatory question every programmer has to answer before starting to get serieus with threads.

    Thanks!
    Last edited by chronozphere; 15-05-2011 at 03:46 PM.
    Coders rule nr 1: Face ur bugz.. dont cage them with code, kill'em with ur cursor.

  2. #2
    for my part my help is pretty limited, sorry , the last time i used thread it wasn't w/o exception management

    oops excepted i used the awful form
    Last edited by farcodev; 28-05-2011 at 04:49 AM.
    Current (and lifetime) project: FAR Colony
    https://www.farcolony.com/

  3. #3
    Can someone else shed any light on this? There must at least be some do's and don'ts on this subject, I suppose.
    Coders rule nr 1: Face ur bugz.. dont cage them with code, kill'em with ur cursor.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •