线程中的异常处理

Posted kinglandsoft

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程中的异常处理相关的知识,希望对你有一定的参考价值。

// Quelle: http://edn.embarcadero.com/article/10452

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
  private
    { Private-Deklarationen }
  public
    { Public-Deklarationen }
  end;

  TMyThread = class(TThread)
  private
    FException: Exception;
    procedure DoHandleException;
  protected
    procedure Execute; override;
    procedure HandleException; virtual;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
begin
  // Create an instance of the TMyThread
  with TMyThread.Create(True) do
  begin
    FreeOnTerminate := True;
    Resume; 
  end;
end;

{ TMyThread }

procedure TMyThread.DoHandleException;
begin
  // Cancel the mouse capture
  if GetCapture <> 0 then SendMessage(GetCapture, WM_CANCELMODE, 0, 0);
  // Now actually show the exception
  if FException is Exception then
    Application.ShowException(FException)
  else
    SysUtils.ShowException(FException, nil);
end;

procedure TMyThread.Execute;
var
  a: Integer;
  b: Integer;
begin
  inherited;
  FException := nil;
  try
    // raise an Exception
    b := 0;
    a := 42 div b;
    Messagebox(0, PansiChar(IntToStr(a)), fehler, 0)
    //raise Exception.Create(‘I raised an exception‘);
  except
    HandleException;
  end;
end;

procedure TMyThread.HandleException;
begin
  // This function is virtual so you can override it
  // and add your own functionality.
  FException := Exception(ExceptObject);
  try
    // Don‘t show EAbort messages
    if not (FException is EAbort) then
      Synchronize(DoHandleException);
  finally
    FException := nil;
  end;

end;

end.

 

以上是关于线程中的异常处理的主要内容,如果未能解决你的问题,请参考以下文章

多线程多线程中的异常处理

C#多线程开发-处理异步操作中的异常

Java子线程中的异常处理(通用)

sop代码未处理系统线程异常

线程中的终极异常处理处理

编写高质量代码改善C#程序的157个建议——建议86:Parallel中的异常处理