线程中的终极异常处理处理
Posted 喜爱糖葫芦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程中的终极异常处理处理相关的知识,希望对你有一定的参考价值。
提问
线程中的终极异常处理处理
回答
- 为了异常阻塞主线程是不值得的
- 使用事件通知方式,这样不会阻塞主线程
- 捕捉AggregateException
线程中的异常处理
// 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.
以上是关于线程中的终极异常处理处理的主要内容,如果未能解决你的问题,请参考以下文章