初在Delphi里进行处理错误时,最常用的做法是try….except ….end. 例如:
复制代码
1
2
3
4
5
6
7
8
9try raise Exception.Create('Error Message'); except on e:Exception do begin ShowMessage(e.Message); end; end;
而现在要说的是另外的一种做法:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14var ExceptionObj : TObject; begin { Simulate an access violation. } try System.Error(reAccessViolation); except ExceptionObj := ExceptObject; if ExceptionObj <> nil then begin MessageDlg(ExceptionObj.ToString, mtError, [mbOK], 0); end; end; end;
在上面的代码,使用了ExceptObject这个对象,这个对象是在System单元中定义的,用于返回当前正在处理的错误对象,如果没有发生错误,其值为nil。当错误变量(在try..except里定义的)不可访问时,ExceptObject就显得很有用,例如当错误处理代码调用一个函数进行错误处理时。
需要注意的是,当错误处理完毕后,ExceptionObject返回的将是nil。还有可能会用到的一个函数是AcquireExceptionObject。这个函数返回当前except 对象的指针,这个函数的作用是为了防止当前的except对象被释放掉。AcquireExceptionObject是通过引用计数进行操作的。
下面是delphi的错误处理的代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76procedure TForm2.btIOErrorClick(Sender: TObject); var ExceptionObj : TObject; begin { Try to write something onto the console--it will raise an exception. } try WriteLn('This will generate an error because there is no' + ' console attached!'); except ExceptionObj := ExceptObject; if ExceptionObj = nil then MessageDlg('No exception', mtError, [mbOK], 0) else begin MessageDlg(ExceptionObj.ToString, mtError, [mbOK], 0); end; end; end; {$OVERFLOWCHECKS ON} {$OPTIMIZATION OFF} {$HINTS OFF} procedure TForm2.btOverflowErrClick(Sender: TObject); var b : Cardinal; ExceptionPtr : Pointer; begin { Simulate an overflow. Note: Enable the overflow checking and disable optimizations, because the Delphi compiler will not compile this code otherwise. } ExceptionPtr := nil; try b := $FFFFFFFF; b := b * b; except ExceptionPtr := AcquireExceptionObject; end; // Check exception. if ExceptionPtr = nil then MessageDlg('No exception', mtError, [mbOK], 0) else begin MessageDlg(TObject(ExceptionPtr).ToString, mtError, [mbOK], 0); ReleaseExceptionObject; end; end; {$HINTS ON} {$OPTIMIZATION ON} {$OVERFLOWCHECKS OFF} procedure TForm2.btRuntimeErrorClick(Sender: TObject); var ExceptionObj : TObject; begin { Simulate an access violation. } try System.Error(reAccessViolation); except ExceptionObj := ExceptObject; if ExceptionObj = nil then MessageDlg('No exception', mtError, [mbOK], 0) else begin MessageDlg(ExceptionObj.ToString, mtError, [mbOK], 0); end; end; end;
转载于:https://www.cnblogs.com/neugls/archive/2011/04/15/2017622.html
最后
以上就是傲娇巨人最近收集整理的关于Delphi Handle Exception的全部内容,更多相关Delphi内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复