如何在Delphi中引发异常?

Iva*_*nov 26 delphi exception

我要求Delphi原生,而不是Prism(net).

这是我的代码:

raise Exception.Create('some test');
Run Code Online (Sandbox Code Playgroud)

未声明的标识符"例外".

问题出在哪里,如何抛出/引发异常?

And*_*den 67

异常类"Exception"在单元SysUtils中声明.因此,您必须在uses-clause中添加"SysUtils".

uses
  SysUtils;

procedure RaiseMyException;
begin
  raise Exception.Create('Hallo World!');
end;
Run Code Online (Sandbox Code Playgroud)

  • 在D2006 +(可能是2005年?)中,您可以使用右键菜单中的"重构 - >查找单元"选项将所需单元添加到您的uses子句中. (16认同)
  • 为了将来参考,通常可以通过在所包含的源代码中搜索您感兴趣的标识符来解决"未声明的标识符"错误.这将告诉您声明它的位置,并且它还可以提供如何使用它的示例. (3认同)

Mar*_*rco 11

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

我还建议你一个很好的方法来跟踪类别,杂乱的格式和异常的含义:

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
Run Code Online (Sandbox Code Playgroud)

一种简单的使用方法是:

TMyException.RaiseError1(123);
Run Code Online (Sandbox Code Playgroud)

  • 已经存在`Exception.CreateFmt`,它支持带有const数组的Format (5认同)
  • @EdwinYip我的意思是`raise Exception.create(format('这是param%d'的异常,[param]));`可以缩短为`raise Exception.CreateFmt('这是param的一个例外%d',[param]);`用较少的击键来做同样的事情 (2认同)

Rob*_*obS 7

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


Wil*_*ill 5

你使用的是SysUtils不是吗?IIRC宣布了例外情况.