2009-07-13 86 views
21

我要求德尔福本土,而不是棱镜(净)。如何在Delphi中引发异常?

这是我的代码:

raise Exception.Create('some test'); 

Undeclarated idenitifier “异常”。

问题在哪里,我该如何抛出异常?

回答

63

在单元SysUtils中声明异常类“Exception”。因此,您必须将“SysUtils”添加到您的使用条款中。

uses 
    SysUtils; 

procedure RaiseMyException; 
begin 
    raise Exception.Create('Hallo World!'); 
end; 
+3

以供将来参考,通过搜索包含您感兴趣的标识符的源代码,可以经常解决“未声明的标识符”错误。这会告诉您它在哪里声明,并且还可以提供如何使用它的示例。 – 2009-07-13 14:32:56

+14

在D2006 +(也许是2005?)中,可以使用右键单击菜单中的“重构 - >查找单元”选项将所需单位添加到您的使用条款中。 – 2009-07-13 21:13:32

5

您正在使用SysUtils不是吗?在IIRC中宣布异常。

7

您可能需要将sysutils添加到uses子句中,它不是内置的,根据Delphi简而言之,它是可选的。

10

请记住将SYSUTILS添加到您的使用单位。

我也建议你一个很好的方法来跟踪类,messagges和异常的意义格式:

Type TMyException=class 
public 
    class procedure RaiseError1(param:integer); 
    class procedure RaiseError2(param1,param2:integer); 
    class procedure RaiseError3(param:string); 
end; 

implementation 

class procedure TMyException.RaiseError1(param:integer); 
begin 
    raise Exception.create(format('This is an exception with param %d',[param])); 
end; 

//declare here other RaiseErrorX 

使用此的一种简单方法是:

TMyException.RaiseError1(123);