Search code examples
delphitry-catchindy

Try except stops the service execution


  List := FQueue.LockList;
  for I := 0 to List.Count - 1 do
  begin
    Mail := TIdMessageTaskman(List[I]);
    FEventLogger.LogMessage(  'Mail' + Mail.ToString, EVENTLOG_INFORMATION_TYPE , 0, 2);
    try
      try
        FidSmtp.Connect();
        FidSmtp.Send(Mail);
      except
        on e: exception do
        begin
          FEventLogger.LogMessage('Error sending mail  ' + e.ClassName + ', ' +
            e.Message, EVENTLOG_ERROR_TYPE, 0, 2);
          MarkMailExecution(Mail.TaskID, Mail.NotificationID, False, e.Message);
          Continue;
        end;
      end;
    finally
      begin
      if FidSmtp.Connected then
      FidSmtp.Disconnect;          
      end;
    end;
    FEventLogger.LogMessage(  'after finally', EVENTLOG_INFORMATION_TYPE , 0, 2);
    MarkMailExecution(Mail.TaskID, Mail.NotificationID, True, '');
    FreeAndNil(Mail)

So the following code works, but as soon as there is a problem sending an e-mail and the exception is raised, the service stops. Is there I way I can make it continue and go through all the Queue? Even if there are messages with errors. For example of an error that stops my service is when "I attach" a file that does not exist.


Solution

  • You said you've confirmed you get into the finally section. So there are 3 possibilities:

    1. A line of code in the finally section blocks the code from continuing.

    2. Another exception is raised in finally section.

    3. When you enter the finally section, you're already in an "exception state". So leaving finally takes you to the next finally/except section in the call stack.

    You'll have to add debug logging to confirm which, but I suspect number 3. Possible triggers for the existing exception state:

    • Your Mail instance is not valid, and your swallower caught an Access Violation. When you again try to use Mail in the except section, you get another Access Violation.

    • Something within MarkMailExecution triggers its own exception.

    • (I'm assuming your logging mechanism isn't failing because you have been getting some information from it.)