2017-05-03 38 views
2

我需要在异常中包含错误代码。在异常处设置ErrorCode

Exceptions (Delphi)

type EInOutError = class(Exception) 
     ErrorCode: Integer; 
    end; 

但我不知道如何设置错误代码。 我想:

type ECustomError= class(Exception) 
     ErrorCode: Integer=129; 
    end; 

但没有成功,我怎么能设置错误代码?

+0

您的代码试图将在其定义中分配一个值。当然,这不是你要找的。您需要在发生异常时分配此信息,对吗?如果是这样,那么在这个异常类上实现一个构造函数,并且当你创建异常时,它会要求你传递这个变量。 –

+0

你想要显示错误代码还是分配给其他的东西,比如功能? –

+0

@NasreddineAbdelillahGalfout只显示。 – strykerbits

回答

10

你不能(也不应该)在类的定义中设置它。这里没有关于被调用的地方和原因的背景。相反,您需要在运行时分配此异常的任何地方。

这可以通过从EInOutError派生类,并添加自定义构造函数,它做:

type 
    ECustomError = class(EInOutError) 
    public 
    constructor Create(AMsg: String; ACode: Integer); reintroduce; 
    end; 

constructor ECustomError.Create(AMsg: String; ACode: Integer); 
begin 
    inherited Create(AMsg); 
    ErrorCode := ACode; 
end; 

然后,当你抛出异常,你怎么称呼它是这样的...

raise ECustomError.Create('Some error message', 129); 

你可以去远一点,这代码添加到您的邮件...

constructor ECustomError.Create(AMsg: String; ACode: Integer); 
begin 
    inherited CreateFmt('%s (Error Code %d)', [AMsg, ACode]); 
    ErrorCode := ACode; 
end; 
+5

另一种方法是根本不派生自定义类:'var E:EInOutError;开始E:= EInOutError.Create('some error message'); E.ErrorCode:= 129;提高E;结束;' –