首页 > 解决方案 > Delphi - 如何处理多种除外类型

问题描述

我愿意用一个特定的函数来处理一些错误,而用另一个函数来处理一些错误。有没有办法在 Delphi 中做到这一点而无需重复整个 'on E:X do' 块?

例如,我有以下代码:

try
  someProcedure()
except
  on E:Error1 do
    thisFunction(E)
  on E:Error2 do
    thisFunction(E)
  on E:Exception do
    thatFunction(E)
end;

是否可以以类似于以下的任何方式编写,避免重复thisFunction

try
  someProcedure()
except
  on E:Error1, Error2 do
    thisFunction(E)
  on E:Exception do
    thatFunction(E)
end;

标签: delphiexception

解决方案


不,该语法是不可能的,正如您在文档中看到的那样。这个限制其实是合理的。确实,如果允许这样的语法,E变量会有什么类型?

但是,您可以使用类层次结构来实现相同的效果。(如果您可以控制异常类,那就是。如果它在逻辑上有意义。)

例如,如果

type
  EScriptException = class(Exception);
    ESyntaxError = class(EScriptException);
    ERuntimeError = class(EScriptException);
      EDivByZeroError = class(ERuntimeError);
      EAverageOfEmptyList = class(ERuntimeError);

然后

try

except
  on E: ESyntaxError do
    HandleSyntaxError(E);
  on E: EDivByZeroError do
    HandleRuntimeError(E);
  on E: EAverageOfEmptyList do
    HandleRuntimeError(E);
end;

可以写

try

except
  on E: ESyntaxError do
    HandleSyntaxError(E);
  on E: ERuntimeError do
    HandleRuntimeError(E);
end;

If you cannot structure your exception classes like this (or if it doesn't make sense logically), you can of course do something along the lines of

try

except
  on E: ESyntaxError do
    HandleSyntaxError(E);
  on E: Exception do
    if (E is EDivByZeroError) or (E is EAverageOfEmptyList) then
      HandleRuntimeError(E);
end;

In fact, if you like, you can catch an exception of the Exception base class and get full programmatic control over the handling:

try

except
  on E: Exception do
    if E is ESyntaxError then
      HandleSyntaxError(E)
    else if (E is EDivByZeroError) or (E is EAverageOfEmptyList) then
      HandleRuntimeError(E)
    else
      raise;
end;

(But beware: what happens if you add a trailing semicolon to the line before the last else?)


推荐阅读